[英]Returning iterator from STL map when using object as a key
I have an issue with returning an iterator from an STL map using an object as a key. 我有一个使用对象作为键从STL映射返回迭代器的问题。
The code compiles when only performing a map.insert(), but will not compile the line attempting to use the iterator returned from a map.insert(). 该代码仅在执行map.insert()时编译,而不会编译试图使用从map.insert()返回的迭代器的行。
The compiler error is "error: no match for 'operator='" 编译器错误为“错误:'operator ='不匹配”
Please see the offending line immediately preceding the return statement in the code snippet below. 请在下面的代码片段中查看return语句之前的有问题的代码行。
Thanks for any assistance! 感谢您的协助!
#include <map>
using namespace std;
class Keys {
public:
Keys(int k1, int k2) :
key1(k1), key2(k2) {
}
bool operator<(const Keys &right) const {
return (key1 < right.key1 && key2 < right.key2);
}
int key1;
int key2;
};
int main() {
std::map<Keys, int> mymap;
map<Keys,int>::iterator myitr;
mymap.insert(std::pair<Keys, int>(Keys(3, 8), 5));
myitr = mymap.insert(std::pair<Keys, int>(Keys(1, 2), 3));
return 0;
}
You need to use an appropriate overloaded function of std::map, that returns an iterator. 您需要使用适当的std :: map重载函数,该函数返回一个迭代器。 For now, you are using std::map::insert with one parameter and it returns std::pair but not an iterator.
现在,您正在使用带有一个参数的std :: map :: insert,它返回std :: pair,但没有迭代器。 You should use this:
您应该使用此:
std::map<>::iterator std::map::insert( iterator _where, value_type val );
So, your code should looks like this: 因此,您的代码应如下所示:
myitr = mymap.insert( std::begin( mymap ), std::make_pair( Keys(1, 2), 3) );
You need to use: 您需要使用:
pair<map<Keys,int>::iterator,bool> ret;
ret = mymap.insert(std::pair<Keys, int>(Keys(1, 2), 3));
Note the return values in the std::map::insert() documentation. 请注意std :: map :: insert()文档中的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.