【问题标题】:Why are Iterators notated as value objects, but referenced as pointers?为什么迭代器被标记为值对象,但被引用为指针?
【发布时间】:2016-09-01 14:07:38
【问题描述】:

在 C++ 标准地图库中,对迭代函数的调用会返回一个迭代器指针,

std::map<int, int> map;
std::map<int, int>::iterator ite = map.find(1);

但是,当使用迭代器时,必须作为指针变量访问,

int first = ite->first;
int second = ite->second;

当我们将从find 函数获得的值放入非指针时,为什么会出现这种情况。正确的语法不应该是:

std::map<int, int>::iterator *pIte = map.find(1)

或者如果使用原始语法,

int first = ite.first;
int second = ite.second;

因为我们获取的是一个值,而不是函数返回值的指针? documentation 中也没有说明。为什么会这样?

【问题讨论】:

  • 迭代器 act 作为指针,在某些情况下是指针。您建议的语法是指向迭代器的指针。
  • sharedunique_ptr 相同,它们是应该像指针一样工作的对象,所以这是有意的。

标签: c++ pointers stl


【解决方案1】:

正如@jaggedSpire 建议的那样,迭代器应该像ptrs 一样,定义了运算符*, -&gt;, etc。但问题是,迭代器不是显式指针。您建议的语法:

std::map<int, int>::iterator *pIte = map.find(1);

是一个指向迭代器的指针,而不仅仅是一个迭代器。你写的原因:

std::map<int, int>::iterator pIte = map.find(1);

你必须写:ite-&gt;first 是因为operator-&gt; 是为迭代器定义的。这意味着迭代器应该像指针一样工作。

【讨论】:

  • 好的,所以它实际上不是一个指针,只是一个行为类似的值类型。我仍然不明白为什么它是这样实现的,但我现在知道它是如何工作的。
  • 这里有一些延伸阅读@iamseiko:cs.northwestern.edu/~riesbeck/programming/c++/…
  • 这有帮助。根据它,迭代器只是它们对应的 Object 指针的 typedef,这更有意义。谢谢。
【解决方案2】:

函数的调用

std::map<int, int>::iterator ite = map.find(1);

返回行为类似于指针的迭代器。

所以你需要使用使用指针访问对象的语法

int first = ite->first;
int second = ite->second;

或者你可以改写

int first = ( *ite ).first;
int second = ( *ite ).second;

例如比较

#include <iostream>
#include <iterator>
#include <algorithm>
#include <utility>

int main()
{
    const size_t N = 5;
    std::pair<int, int> a[N] = { { 2, 2 }, { 4, 4 }, { 1, 1 }, { 3, 3 }, { 5, 5 } };

    std::pair<int, int> *it = std::find( std::begin( a ), std::end( a ), std::make_pair( 1, 1 ) );

    if ( it != std::end( a ) )
    {
        std::cout << it - a << ": "
                  << "{ " << it->first << ", " << it->second << " }" << std::endl; 
    }

    return 0;
}

程序输出是

2: { 1, 1 }

这里it 被显式声明为指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多