gpt4 book ai didi

c++ - 在 std::map 中打印迭代器的索引

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:31 25 4
gpt4 key购买 nike

我正在使用 std::mapfind() 方法,它返回一个迭代器
但是我需要找到的元素的索引;例如:0,对应于std::map::begin(),等等。

#include <map>
#include <utility>
#include <iostream>

int main()
{
std::map< int, int > aMap;
aMap.insert( std::make_pair(100, 50) );
aMap.insert( std::make_pair(200, 40) );
aMap.insert( std::make_pair(300, 60) );

std::map< int, int >::iterator it_map = aMap.find(300);
if (it_map != aMap.end())
std::cout << it_map << "\n"; // error

}

那不编译,我知道原因。但是,我需要一种打印 2 的方法,因为 300 的索引是 2。

对于那个简单的例子,你可能会说map(二叉树)不是一个好的容器。但是,在实际代码中,我必须搜索大量元素,而二叉树非常适合搜索。

有什么想法吗?

最佳答案

如果您需要索引,那么 map 可能是错误的数据类型;您需要遍历映射(以线性时间)以找到索引,从而失去对数时间搜索的优势。

也许使用 lower_bound 算法以对数时间查找元素的排序 vector 可能更合适。然后,您可以在常数时间内从 begin() 迭代器中减去生成的随机访问迭代器。

不过,如果您确实想使用 map :

std::cout << std::distance(aMap.begin(), it_map) << '\n';

关于c++ - 在 std::map 中打印迭代器的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871606/

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