map<int, int> m;
m[-1]=1;
m[45]=100;
m[20]=3;
// -1<20<45. So The index of (-1, 1) is 0; (45, 100) is 2; (20, 3) is 1;
// "find" function returns the iterator, but how to know its order?
number = m.find(45) - m.begin(); // This is apparently not correct.
如何在知道 map 中的键后找到索引?
最佳答案
map 中没有索引,只有迭代器。
要获取迭代器,你可以这样做:
std::map<int, int>::iterator it = m.find(45);
如果你真的想找到“距离”,你可以这样做:
auto dist = std::distance(m.begin(),m.find(45));
关于c++ - 在 C++ 中为映射获取具有指定键的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772268/