2015-07-03 105 views
0

我寫這篇文章的代碼和我得到這個錯誤解引用一個迭代器:錯誤在C++設置和矢量

[Error] passing 'const std::vector' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = metastock7, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::value_type = metastock7]' discards qualifiers [-fpermissive]

struct A{ 
    string name; 
    vector<B> rows; 
}; 
set<A, classcomp> set; 
vector<B> data; //I filled the vector in my code 
std::set<A, classcomp>::iterator it; 
std::pair<std::set<A, classcomp>::iterator,bool> ret; 
for(int i = 0; i < data.size(); i++){ 
    A a; 
    B b = data[i]; 
    a.name= b.name; 
    ret = set.insert(a); 
    it = ret.first; 
    (*it).rows.push_back(b); //IT COMPILES WITHOUT 
    // it->rows.push_back(mstk7); //fails as well 
} 

我真的不理解的錯誤。你能幫忙嗎?

謝謝。

回答

2

std::set是一個有序的容器,所以它不允許你直接修改它的元素。如果是這樣,您可以使其訂單保證無效。

要修改元素,您需要將其複製,從集合中刪除,修改它,然後重新插入它。如果您發現自己需要經常這樣做,您可能需要考慮使用不同的容器類型,特別是因爲複製您的會員可能會變得昂貴。

+1

也許使用'map'會更理想 –

+0

謝謝!我選擇設置只是因爲它不允許重複。是否有其他容器不允許重複? – user3665096

+0

正如@OlivierPoulin所說,你可能會更喜歡'name'和'rows'之間的映射。看看['std :: map'](http://www.cplusplus.com/reference/map/map/)和['std :: unordered_map'](http://en.cppreference.com/瓦特/ CPP /容器/ unordered_map)。 – TartanLlama