尝试从容器中获取迭代器时编译错误

时间:2011-11-30 22:44:04

标签: c++

我收到以下错误:

error: conversion from 'std::vector<shape*>::const_iterator 
to non-scalar type 'std::vector<shape*>::iterator

有人可以向我解释发生了什么事吗?

template <typename Container>
void draw_all(const Container &c)
{
    for (typename Container::iterator p= c.begin(); p != c.end(); p++)
    {
        (*p)->draw();
    }
}

vector<shape *> vs;
draw_all(vs);

3 个答案:

答案 0 :(得分:6)

错误消息的确如此:您正在尝试从const对象获取非const迭代器。而是做:

typename Container::const_iterator p = c.begin();

答案 1 :(得分:2)

您有const Container,并且在其上调用begin()将为您提供const_iterator,而不是iterator(因为您不允许修改内容) 。所以请改用const_iterator,或者使用非const引用作为输入。

显然,如果你使用draw()const_iterator也被认为是一个const成员函数。

答案 2 :(得分:1)

您的容器是一个常量引用,因此您只能在其上使用const_iterator并且只能调用const方法。尝试改为

template <typename Container>
void draw_all(Container &c)
{
    for (typename Container::iterator p= c.begin(); p != c.end(); p++)
    {
        (*p)->draw();
    }
}

或制作迭代器和draw()方法const