gpt4 book ai didi

c++ - C++ 中特定位置映射的迭代器

转载 作者:太空狗 更新时间:2023-10-29 20:03:47 26 4
gpt4 key购买 nike

我有一个元素映射和一个迭代它的嵌套循环。但我希望迭代器表现得像这样:

    map<int,int>::iterator it;
map<int,int>::iterator it1;
bool flag=false;

for(it=m.begin();it!= m.end()-1;it++)
{
for(it1 = it+1;it1 != m.end();it1++)
{
if((it->first < it1->first)&&(it->second > it1->second))
{
flag=true;
break;
}
}
}

基本上,外循环应该从最后一个位置开始终止,内循环必须从外循环迭代器所在的位置开始迭代。但是这段代码似乎不起作用。(No Match for + in it+1) is not defined 任何帮助将不胜感激。 (请指出任何重复的链接,因为我找不到 map 链接。)谢谢!

最佳答案

std::map<K,V,C,A>::iterator bidirectional iterator , 这意味着它不提供 operator+都不是operator- (只有前缀和后缀形式的 operator++operator--)。

仍然可以使用 std::next() 移动迭代器或 std::prev() :

for (it = m.begin(); it != std::prev(m.end()); ++it)
// ~~~~~~~~^ instead of m.end()-1
{
for (it1 = std::next(it); it1 != m.end(); ++it1)
// ~~~~~~~~^ to get the it+1

你可以使用 std::advance() 而不是按给定的时间间隔向前/向后移动(不同之处在于它对实际对象进行操作,而不是创建像 std::next 这样的拷贝):

it1 = it;
for (std::advance(it1, 1); it1 != m.end(); ++it1)
// ~~~~~~^ ^ number of steps

这两种方法都提供了递增/递减给定迭代器的最佳方式(基于该迭代器的特征)。

关于c++ - C++ 中特定位置映射的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872817/

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