1

In this code:

string s = "hello";

for(auto i : s)
{
    i = 'p';
    cout<<i<<'\n';
} 
cout<<s<<endl;

the output will be:

p
p
p
p
p
hello

So when i is used to refer to the next element in string s it is not an iterator but a dereferenced iterator? Had it been auto &i it would certainly have changed the value of string s pointing that it is dereferenced iterator. Is it correct?

Agrudge Amicus
  • 1,033
  • 7
  • 19
  • 1
    Yes. Now, read [this](https://en.cppreference.com/w/cpp/language/auto) and [this](https://en.cppreference.com/w/cpp/language/template_argument_deduction#Other_contexts), and preferably avoid using `auto` in general. – paddy Jul 21 '20 at 05:49

1 Answers1

-1

So when i is used to refer to the next element in string s it is not an iterator but a dereferenced iterator?

Kind of.
i copies the value of the iterator position in s. It's not a reference. In most use cases, the i value is not expected to be changed, then you may use:

for(const auto& i : s)

Had it been auto &i it would certainly have changed the value of string s pointing that it is dereferenced iterator. Is it correct?

Yes. for(auto& i : s), makes the s modifiable due to i.

iammilind
  • 68,093
  • 33
  • 169
  • 336