为什么迭代器被标记为值对象,但被引用为指针?

时间:2016-09-01 14:07:39

标签: c++ pointers stl

在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中也没有澄清。为什么会这样?

2 个答案:

答案 0 :(得分:1)

正如@jaggedSpire建议的那样,迭代器应该像ptrs一样,定义了运算符*, ->, etc。但事实是,迭代器不是一个明确的指针。你建议的语法:

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

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

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

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

答案 1 :(得分:0)

调用函数

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显式声明为指针。