I'm new to C++ and is trying to learn the concept of vector. I saw this code online. My question is, what is purpose of the inner for-loop inside 'for(auto &str : vec)'? Why did the author created a second reference (&c) to the first reference (&str)?
int main() {
vector<string> vec;
for (string word; cin >> word; vec.push_back(word)) {
}
for (auto &str : vec) {
for (auto &c : str) {
c = toupper(c);
}
}
for (int i = 0; i != vec.size(); ++i) {
if (i != 0 && i % 8 == 0) cout << endl;
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
It is for converting every character of the string str
to uppercase.
In other words, this:
for(auto &c : str) {
c = toupper(c);
}
is equivalent to:
for(size_t i = 0; i < str.size(); ++i) {
str[i] = toupper(str[i]);
}
The first loop goes over the vector of strings one string at a time. The inner loop, for each string, goes over each character of the string. So c
is a reference to a character in str
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With