gpt4 book ai didi

c++ - 在 std::map 中的给定迭代器位置之后继续循环

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

我想遍历 map 中给定项目之后的所有项目。

不幸的是,我收到错误:“operator+”不匹配(操作数类型为“std::_Rb_tree_iterator >”和“int”)。

我做错了什么?

#include <iostream>
#include <map>

int main ()
{
std::map<char,int> m = {
{'a',1},{'b',2},{'c',3},{'d',4},
};

// Position at 'b' (the 'given item')
auto it = m.find('b');

// Output everything after 'b':
for (auto it1=it+1; it1!=m.end(); ++it1) {
std::cout << it1->first << " => " << it1->second << '\n';
}

return 0;
}

最佳答案

std::map 的迭代器不是随机访问的,因此它没有 operator+()。您需要使用 std::next() 代替:

 for (auto it1=std::next(it); it1!=m.end(); ++it1) {
std::cout << it1->first << " => " << it1->second << '\n';
}

关于c++ - 在 std::map 中的给定迭代器位置之后继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709108/

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