C++中特定位置的映射的迭代器
Iterator for a map from a particular position in C++
我有一个元素映射和一个嵌套循环来迭代它。但我希望迭代器的行为如下:
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;
}
}
}
基本上,外循环应该在倒数第二个位置开始终止,内循环必须从外循环迭代器所在的位置开始迭代。但这段代码似乎不起作用。(不匹配it+1中的+)未定义。如有任何帮助,我们将不胜感激。(请指出任何重复的链接,因为我找不到地图。)谢谢!
std::map<K,V,C,A>::iterator
是一个双向迭代器,这意味着它既不提供operator+
也不提供operator-
(只有前缀和postifx形式的operator++
和operator--
)。
在c++11中,仍然可以使用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
在c++03中,您可以使用std::advance()
按给定的间隔向前/向后移动(不同之处在于它对实际对象进行操作,而不是像std::next
那样创建副本):
it1 = it;
for (std::advance(it1, 1); it1 != m.end(); ++it1)
// ~~~~~~^ ^ number of steps
这两种方法都提供了对给定迭代器进行递增/递减的最佳方式(基于迭代器的特性)。
这样的事情也应该起作用。
map<int,int>::iterator it = m.begin();
map<int,int>::iterator end = m.end();
map<int,int>::iterator it1;
bool flag=false;
if ( it != end )
{
--end;
}
for(it; it != end; it++)
{
it1 = it;
for(++it1; it1 != m.end(); it1++)
{
if((it->first < it1->first)&&(it->second > it1->second))
{
flag=true;
break;
}
}
}
相关文章:
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 映射迭代器与运算符不匹配
- 我可以将映射迭代器与 OpenMP 并行使用吗?
- 取消引用映射迭代器时返回对临时的引用
- 为什么映射迭代器显示基本操作数无效错误
- 复制映射迭代器对值的省略
- ->第一个/第二个到空映射迭代器开始
- 由引用集/映射迭代器传递的迭代器不可取消引用
- 在 GCC 上自动声明映射迭代器错误
- 指向同一项的两个映射迭代器是否保证相等
- 嵌套映射迭代器
- 模板标准::映射::迭代器实例化
- 映射迭代器遍历技术
- 映射迭代器与手动
- VC++11映射和多映射迭代器(重载)C2535
- 切换情况下映射迭代器的交叉初始化
- C++-映射迭代器中的if语句导致程序崩溃的原因
- 映射迭代器:一元'*'的无效类型参数(具有"int")
- 比较未引用的映射迭代器(std::pairs):C2678
- 与C++中擦除映射迭代器的行为不一致