简体   繁体   中英

Map iterator no match for operator

I have no match for operator in map iterator. When I try to make the iterator it points to the map end-1.

#include <iostream>
#include <map>
int main()
{
    std::map<char,int> mymap;

    mymap['b'] = 100;
    mymap['a'] = 200;
    mymap['c'] = 300;

    // show content:
    for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end()-1; ++it){
        std::cout << it->first << " => " << it->second << '\n';
    }
    return 0;
}

This statement

mymap.end()-1

is only legal for Random Access Iterator but std::map::iterator is Bidirectional Iterator . If you want to skip last element use std::prev()

for (std::map<char,int>::iterator it=mymap.begin(); it!=std::prev( mymap.end() ); ++it)

though it is not efficient to always calculate it and it should be instead:

 auto end = std::prev( mymap.end() );
 for (auto it=mymap.begin(); it!=end; ++it) ...

Note for this to work you have to be sure that there is at least one element in your map. If you do not want to skip the last element remove -1 completely.

没有操作符-用于地图迭代器,但这没关系,因为如果您想显示所有内容,应该就是it!=mymap.end();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM