在 C++ Set 和 Vector 中取消引用迭代器时出错

Error dereferencing an iterator in C++ Set and Vector

我在编写这段代码时遇到了这个错误:

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

我真的不明白错误。你能帮忙吗?

谢谢。

std::set 是一个有序的容器,所以它不允许你直接修改它的元素。如果是这样,您可以使其订购保证无效。

要修改元素,您需要复制它,从集合中删除它,修改它,然后重新插入它。如果您发现自己经常需要这样做,您可能需要考虑使用不同的容器类型,尤其是因为复制您的 std::vector 成员可能会很昂贵。