c++ - 在 C++ 中为映射获取具有指定键的索引

标签 c++ stl

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/

相关文章:

c++ - 如何使用CreateDIBSection在BITMAPINFO中写入颜色数据?

c++ - 我的代码如何在编译时做一件事,而在运行时做另一件事?

C++ STL : How to iterate vector while requiring access to element and its index?

c++ - 运行程序的确切时间是多少?

c++ - 为什么使用 vector 会出现链接器错误?

c++ - 指示 GCC 链接为 C++

c++ - 如何在没有初始化 shared_ptr 对象的情况下初始化对象的管理器?

c++ - 如何在 Visual C++ 中对 x64 项目运行代码分析?

c++ - 理解 C++ 映射为什么不使用 clear() 释放堆内存?

从完整二叉搜索树顺序转换为排序顺序的算法,反之亦然