For vs Iterator

I'm attempting to understand a few concepts, and think i'm on the right track, but am looking for feedback if i'm right or wrong. As I understand it, auto is a substitute for declaring the variable type, and the variable will became whatever it needs to be, string, char, etc. Also, the benefit of using iterators instead of the for loop, is it is flexible for other STL containers, so if I wanted to change a vector to map, I wouldn't need to change anything in that loop? Thank you for your time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    vector<string> inventory { "Sword", "Axe", "Shield"};
    for ( auto x : inventory )
    {
        cout << x << endl;
    }
    for_each(inventory.begin(), inventory.end(), [](string &n){ n = "Empty"; });
    for ( auto x : inventory )
    {
        cout << x << endl;
    }
    return 0;
}
std::for_each, as well as a for loop that uses iterators (for(auto i = v.begin(); i != v.end(); ++i)), works with any pair of iterators: this is the most general concept. The pair of iterators may be vector iterators, input stream iterators, counting iterators, transform iterators, etc, and they'd all be handled the same way.

range for loop (your for(auto x : inventory)) is a lot more specific: it only (with a small exception) works with things that have the begin() and end() member or non-member functions, which return iterators: you can use it with a vector or with a map, but not with an input stream.
Last edited on
range for loop (your for(auto x : inventory)) is a lot more specific: it only (with a small exception) works with things that have the begin() and end() member or non-member functions, which return iterators: you can use it with a vector or with a map, but not with an input stream.

Does this include string objects as well, if I understand correctly?
yes. std::string has begin() and end as member functions, and string literals (sequences of characters in double quotes, which are actually arrays) have begin() and end() as non-member functions:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
int main()
{
     std::string s = "abc";
     for(auto ch : s)
          std::cout << ch << ' ';
     for(auto ch : "def")
          std::cout << ch << ' ';
}
Topic archived. No new replies allowed.