c++ 函数返回迭代器失效-代码导致问题
今天想根据value从map中的到对应的迭代器,如果没找到返回end(),但是实现的时候函数里面找得到对应的迭代器,返回后就不对了,找了半天发现是,函数传参map时候没有用引用,导致map是复制的,导致对应的迭代器也不同.记录一下.警示!
#include <iostream>
#include <map>
#include <string>
std::map<int, std::string> mp;
// !!!这里的参数std::map<int, std::string> &mp 需要引用否则导致复制map不是同一个
std::map<int, std::string>::iterator getIteratorByValue(std::map<int, std::string> &mp , std::string value) {
auto it = mp.begin();
while (it != mp.end()) {
if (it->second == value) {
return it;
}
it++;
}
return mp.end();
}
int main() {
mp[0] = "a";
mp[1] = "b";
mp[2] = "c";
std::map<int, std::string>::iterator it = getIteratorByValue(mp, "b");
}