通过迭代器更改类成员 [英] Changing a classes member through an iterator

查看:165
本文介绍了通过迭代器更改类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,不能解决这个问题:

I'm learning C++ and can't get my head around this problem:

我有一个简单的类A

class A {
private:
    int ival;
    float fval;

public:
    A(int i = 0, float f = 0.0) : ival(i), fval(f) { }
    ~A(){ }
    void show() const { 
        cout << ival << " : " << fval << "\n";
    }
    void setVal(int i) {
        ival = i;
    }

    //const getters for both ival and fval

    //used for the default "lesser"
    friend bool operator<(const A& val1, const A& val2) {
        return val1.ival < val2.ival ? true : false;;
    }
}

set< A>

Then I have a regular set<A> myset that gets filled with insert(A(2, 2.2)); in a loop.

迭代获取所有值不是问题,但我想修改此迭代中的值:

Iterating to get all the values is not a problem but I want to modify the value within this iteration:

for(set<A>::iterator iter = set3.begin(); iter != set3.end(); iter++) {
    iter->setVal(1);
}



我假设这应该是可行的,就像你在Java一个foreach循环。当编译时,我得到错误:传递'const A'as'this'参数'void A :: setVal(int)'丢弃限定符

查看STL集合的来源,我看到 begin()只能作为const方法使用我认为这可能是问题。使用const在 setVal()方法总是有相同的错误,并没有什么意义,因为我想修改 A 。

Looking at the sources of the STL set, i see that begin() is only available as a const method and I think this might be the problem. Messing around with const on the setVal() method got always the same error and wouldn't make much sense since I want to modify the value of A.

这是改变一堆 A 的错误方法有一个循环?

Is this the wrong approach of changing a bunch of A's values with a loop?

推荐答案

STL集不允许你改变它存储的值。它通过返回一个对象的副本通过迭代器(而不是实际的集合)。

The STL set does not let you change values it stores. It does that by returning a copy of the object through the iterator (not the actual one in the set).

这样做的原因是因为它使用<并且它不想在每次取消引用迭代器时重新生成整个树,因为它不知道你是否更改了任何改变顺序的内容。

The reason that set does this is because it's using < to order the set and it doesn't want to remake the entire tree every time you dereference the iterator, which it would have to do, since it doesn't know if you changed anything that changes the ordering.

如果您需要更新set<>,请删除旧值并添加一个新值。

If you need to update the set<>, remove the old value and add in a new one.

编辑:刚刚检查SGI STL的来源,它说:

just checked source to SGI STL and it says this:

 typedef typename _Rep_type::const_iterator iterator;

因此,set :: iterator只是一个set :: const_iterator

So, a set::iterator is just a set::const_iterator

这篇关于通过迭代器更改类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆