I have a vector of a map of int and float
std::vector<std::map<int, float>> datad;
And I want to iterate over the maps in vector and inside over pairs in map
for (std::vector<std::map<int, float>>::iterator currentMap = datad.begin(); currentMap < datad.end(); currentMap)
{
for (std::map<int, float>::iterator it = currentMap->begin(); it < currentMap->end(); it)
{/*some code here*/}
}
But in the second loop g
compiler gives an error:
no match for ‘operator<’ (operand types are ‘std::_Rb_tree_iterator<std::pair<const int, float> >’ and ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’})
But isn't it looks like the types
std::_Rb_tree_iterator<std::pair<const int, float>>
std::_Rb_tree_iterator<std::pair<const int, float>>
are the same?
Yes, I see that compiler says the currentMap->end()
have the type std::map<int, float>::iterator
but...it is aka _Rb_tree_iterator
...
maybe
static_cast<std::_Rb_tree_iterator<std::pair<const int, float>>>(currentMap->end())
What is the easiest way to continue using iterators and fix the problem?
PS. static_cast don't work, it gives
no match for ‘operator<’ (operand types are ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’} and ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’})
PSS. I've also tried auto
but it also doesn't work (the same error as the first one)
CodePudding user response:
std::map
's iterators are bidirectional iterators, not random access iterators. Therefore they do not provide relational comparison operators. You can only equality-compare them.
So replace <
with !=
, which is the standard way of writing iterator loops. Or even better, replace the loop with a range-for loop:
for (auto& currentMap : datad)
{
for (auto& el : currentMap)
{
/* Use el here as reference to the (pair) element of the map. */
}
}