Reputation: 35
I am a novice C++ programmer working through a simple problem to print out name-and-score pairs together. Here I have used a std::unordered_set
for the names and a vector for the scores (to accept duplicate scores, but not names) and that works fine.
But one thing puzzles me about the result, and that's that if I try to initialize the iterator in the for loop, the compiler gives me an error that says
the iterator "cannot be defined in the current scope."
This gives the error:
for (int i = 0, std::unordered_set<std::string>::iterator it = names.begin();
i < names.size(); i++, it++)
{
std::cout << *it << ", " << scores[i] << '\n';
}
But moved outside the loop, it works fine:
std::unordered_set<std::string>::iterator it = names.begin();
for (int i = 0; i < names.size(); i++, it++)
{
std::cout << *it << ", " << scores[i] << '\n';
}
Why must the iterator be initialized outside the loop here? Sorry for the simple question, I've searched elsewhere and have not found a clear answer for this.
Upvotes: 2
Views: 389
Reputation: 32722
In C++ for-
loop
for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) )
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
init-statement
- either an expression statement (which may be a null statement ";")
- a simple declaration, typically a declaration of a loop counter variable with initializer, but it may declare arbitrary many variables Note that any init-statement must end with a semicolon ;, which is why it is often described informally as an expression or a declaration followed by a semicolon.
Therefore, you can either declare the variable of the same type; ex:
for (int i = 0, j = 1; ... ; i++, j++) {...}
^^^^^^^^^^^^^^^^
or initialize the variables of any type that you have declared previously. Ex
std::unordered_set<std::string>::iterator it;
int i;
for (it = names.begin(), i = 0; i < names.size(); i++, it++) { ... }
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Hence, your attempt is failed.
Upvotes: 3