gpt4 book ai didi

c++ - 减少 std::map 的结尾

转载 作者:IT老高 更新时间:2023-10-28 12:50:05 25 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <map>
using namespace std;

int main() {
map<int , int > myMap;

map<int , int>::iterator it;

myMap.insert(pair<int , int>(1,2));
myMap.insert(pair<int , int>(671,223));
myMap.insert(pair<int , int>(353,245352));

it = myMap.end() - 1;

cout << it->first << it->second << endl;

return 0;
}

编译此代码会产生以下编译错误:

error: no match for ‘operator-’ (operand types are ‘std::map<int, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const int, int> >}’ and ‘int’)
it = myMap.end() - 1;

我不知道为什么会出现此错误,因为我认为所有类型的迭代器都允许算术运算。

最佳答案

并非所有迭代器类别都支持算术运算,这是一种误解。如果您的目标是编写更通用的代码,您可以使用 std::prev :

it = std::prev(myMap.end());

它需要一个双向迭代器,即 std::map 的迭代器。如果你想移动迭代器不止一步,它还可以接受第二个参数,指定移动迭代器的距离。

另外,当你给它传递一个随机访问迭代器时,它会和算术一样快。

关于c++ - 减少 std::map 的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640199/

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