Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is purpose of the inner for-loop inside 'for(auto &str : vec)'?

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;
}
like image 433
Thor Avatar asked Feb 08 '23 19:02

Thor


2 Answers

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]);
}
like image 74
Humam Helfawi Avatar answered Mar 07 '23 11:03

Humam Helfawi


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.

like image 32
Shoe Avatar answered Mar 07 '23 11:03

Shoe