在C ++中将std :: map迭代器初始化为零 [英] std::map iterator initialization by zero in C++

查看:166
本文介绍了在C ++中将std :: map迭代器初始化为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过零值初始化一个插入器.我尝试了以下代码

I need to initialize an interator by zero value. I tried following code

#include <map>
std::map<int, int>::iterator foo() {
    std::map<int, int>::iterator ret;
    ret = std::map<int, int>::iterator(0);
    return ret;
}

它已在Linux上由gcc和intel C ++编译器成功编译.此外,在Windows上的minGW中,此编译良好. -O2提供的代码是

It successfully compiled by gcc and intel C++ compilers on Linux. Also, this compiled well in minGW on Windows. The code provided with -O2 is

xorl eax, eax
ret

问题是在Visual Studio下进行编译.错误是: 错误C2440:'':无法从'int'转换为'std :: _ Tree_iterator >>>没有构造函数可以采用源类型,或者构造函数重载分辨率不明确.

The issue is compilation under VisualStudio. The error is: error C2440: '' : cannot convert from 'int' to 'std::_Tree_iterator>>> No constructor could take the source type, or constructor overload resolution was ambiguous.

您能否给我一个想法,如何转换为零或重新定义迭代器的初始化?

Could you please give me an idea how to cast zero or rephrase initialization of iterator?

谢谢

PS

主要思想是在列表"末尾获得NULL

main idea is getting NULL at the end of the "list"

(it = a.begin(); it!= a.end(); it = it-> next)

(it = a.begin(); it != a.end(); it = it->next)

基于不同地图对象的map :: iterators的.

that based on map::iterators from diffrent map objects.

a::end() {
    return std::map<K, V>::iterator(0)
}

推荐答案

不,您没有.

您需要使用 past-the-end 值初始化(只能从应该迭代的容器中获取):

You need to initialize either with past-the-end value (which you can only get from the container it is supposed to iterate):

return map.end();

,或者在最差的情况下使用默认值:

or at worst with default value:

return std::map<int, int>::iterator();

区别在于,可以测试前者是否为最终迭代器,而后者基本上是不可触及的.如果您稍后再做,则基本上必须记住不要触摸它.您甚至无法比较默认构造的迭代器是否相等,以检查它们是否是默认构造的(大多数实现定义了比较,但有些实现则不是).

The difference is that the former can be tested whether it is end iterator, while the later is basically untouchable. If you do the later, you basically have to remember not to touch it. You can't even compare default-constructed iterators for equality to check that they are default-constructed (most implementations define the comparison, but some may not).

这篇关于在C ++中将std :: map迭代器初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆