Error dereferencing an iterator in C++ Set and Vector

微笑、不失礼 提交于 2019-12-31 05:39:08

问题


I'm writing this code and I'm getting this error:

[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
}

I really don't understand the error. Can you please help?

Thank you.


回答1:


std::set is an ordered container, so it doesn't allow you to directly modify its elements. If it did, you could invalidate its ordering guarantees.

To modify the element, you'd need to copy it, erase it from the set, modify it, then reinsert it. If you find yourself needing to do this often, you might want to consider using a different container type, especially as copying your std::vector member could get expensive.



来源:https://stackoverflow.com/questions/31209529/error-dereferencing-an-iterator-in-c-set-and-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!