简体   繁体   English

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

[英]Error dereferencing an iterator in C++ Set and Vector

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] [错误] 将 'const std::vector' 作为 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = metastock7, _Alloc = std::allocator, std: :vector<_Tp, _Alloc>::value_type = metastock7]' 丢弃限定符 [-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.谢谢你。

std::set is an ordered container, so it doesn't allow you to directly modify its elements. std::set是一个有序的容器,所以它不允许你直接修改它的元素。 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.如果您发现自己需要经常这样做,您可能需要考虑使用不同的容器类型,尤其是复制std::vector成员可能会很昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM