gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:28:22 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com