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.