2013-03-27 102 views
3

enter image description here迭代通过一个std ::矢量

为什么问我重载运算符=? 我以前通过一个std :: list迭代,我没有这样的问题。

class Grup : public Shape { 

private: 

    std::vector<Shape*> continut; 

public: 

    static const std::string identifier; 

    Grup(); 
    ~Grup(); 

    void add(Shape *shape); 
    void remove(Shape *shape); 
    void output(std::ostream &outs) const; 
    void readFrom(std::istream &ins); 
    void moveBy(int x, int y); 

    friend std::ostream &operator<<(std::ostream &outs, const Grup &grup); 
}; 


std::ostream &operator<<(std::ostream &outs, const Grup &grup) 
{ 

std::vector<Shape*>::iterator it; 

    outs << "Grupul este format din: " << std::endl; 

    for (it = continut.begin(); it != continut.end(); it++) 
    { 

    }  

    return outs; 
} 

错误: “没有可行的超载 '='。”

+0

请打印的代码,截图是不够明确以及如何'Grup'定义? – 2013-03-27 10:49:11

回答

5

(截图的放大之后)grup被传递在作为const,所以begin()将返回不能被分配给iterator一个const_iterator 。的it

更改声明:

std::vector<Shape*>::const_iterator it; 

注意在C++ 11可以使用auto来指示编译器推断类型:

for (auto it = grup.continut.begin(); it != grup.continut.end(); it++) 
{ 
    outs << **s << std::endl; 
} 

在C其它替代方案++ 11是range-based for loop

for (auto& shape: grub.continut) 
{ 
    outs << *s << std::endl; 
} 

std::for_each()lambda

std::for_each(grub.continut.begin(), 
       grub.continut.end(), 
       [&](Shape* s) { outs << *s << std::endl; }); 
+0

哦,我明白了,谢谢。 – Teodora 2013-03-27 10:55:40

+0

第一种for不起作用。它应该是* s – Teodora 2013-03-27 11:07:23

+0

@Teodora,它取决于是否存在对operator <<(std :: ostream&,const Shape&)的重载。在第一个'for'中,'iterator'需要解引用来访问'Shape *',然后'Shape *'需要解除引用。 – hmjd 2013-03-27 11:11:33

3

变化:

std::vector<Shape *>::iterator it; 

到:

std::vector<Shape *>::const_iterator it; 
         ^^^^^^ 

当你传递一个const Grup参考。

或者,如果使用的是C++ 11:

for (auto it = grup.continut.begin(); it != grup.continut.end(); ++it) 
{ 
    ... 
} 
+0

谢谢。这是问题所在。 – Teodora 2013-03-27 10:53:38