Changing element of vector does not persist or does iteration make a copy

I a noob, so I apologize in advance. :) Based on the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::vector<std::string> v1;
v1.push_back("bbbb");
v1.push_back("cccc");
for(std::vector<std::string>::iterator iter = v1.begin();
        iter != v1.end(); ++iter) {
  std::string word = *iter;
  word[0] = 'A';
  std::cout << word << std::endl;
}
for(std::vector<std::string>::iterator iter = v1.begin();
        iter != v1.end(); ++iter) {
  std::string word = *iter;
  std::cout << word << std::endl;
}


I would expect:

Abbb
Accc
Abbb
Accc

but it is in fact:

Abbb
Accc
bbbb
cccc

My guess is that the iterator is making a copy of the data? That is I am not iteratoring over v1, I am iteratoring over a copy?
In line 6 you are making a copy yourself :) You take the value of iter, store it in word and then change it, but you never change the original strings in the vector.
I see, the = operator does a copy. Very interesting!
Just to illustrate I changed the top loop to:

1
2
3
          std::string* word = &(*iter);
          (*word)[0] = 'A';
          std::cout << *word << std::endl;


and it did work as I expected/.

Thank you!!
Though the word variable is not really needed in that case. For example:
1
2
3
    (*iter)[0] = 'A';
    iter->at(3) = 'Z';
    std::cout << *iter << std::endl;
Correct, I just prefer a temp variable...
Well, there's nothing wrong with having a preference. Though I saw it as clutter, my preference is to keep the code simple, direct and to the point.
References to the rescue!
std::string& word = *iter;
Topic archived. No new replies allowed.