2013-03-27 103 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