使用iterator在STL Set中调用非静态函数 [英] Use iterator to call the non-static function in STL Set

查看:201
本文介绍了使用iterator在STL Set中调用非静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,我有一个具有非静态函数 void add()的类 A 。我想使用迭代器为集合中的每个元素调用 add(),但在最后一个元素有错误。

In the following program, I have a class A with a non-static function void add(). I want use the iterator to call add() for each element in the set, but there is a error at the last element.

我如何修复它?

#include <iostream>
#include <set>

using namespace std;

class A
{
private:
    int a;
public:
    A(int x) { a = x; }
    void add() {a = a + 1; }
    bool operator<(A x) const { return a < x.a; }
};

int main()
{
    //type of the collection
    typedef set<A> IntSet;

    //define a IntSet type collection
    IntSet col1;
    IntSet::iterator pos;

    //insert some elements in arbitrary order
    col1.insert(A(3));
    col1.insert(A(4));
    col1.insert(A(5));

    //iterator over the collection and print all elements

    for(pos = col1.begin(); pos != col1.end(); ++pos)
    {
        (*pos).add();
        // ERROR!: Member function 'add' not viable:
        // 'this' argument has type'const value_type' 
        // (aka 'const A'), but function is not marked const
    }
    cout << endl;
}


推荐答案

c $ c> set<> 容器被视为 const ,无法修改。如果他们这样做,他们的身份可能改变,但是 set<> 不会意识到这一点,破坏其内部结构,因为项目将被存储在桶中它不属于

Items contained in a set<> container are considered const and cannot be modified. If they did, their identity might change but set<> wouldn't be aware of this, wreaking havoc on its internal structure as an item would be stored in a bucket where it didn't belong!

例如,考虑 set<> 使用您的自定义 operator< 重载为了排序其内容。如果在对象包含在集合中时更改 a 成员变量,则会发生什么情况?该集合不会知道 a 已更改,并会将对象留在其中。

Consider, for example, that set<> uses your custom operator< overload in order to sort its contents. What would you expect to happen if you change the a member variable while the object is contained in a set? The set won't know that a changed and will leave the object where it was.

要修复此潜在问题问题, set<> 只能引用包含对象的 const 实例。

To fix this potential problem, set<> only gives you references to const instances of contained objects.

您只能在此上下文中使用 const 类的成员,并且 add()未声明 const 。如果要修改对象并将这些更改反映到集合中,则必须创建对象的副本,从集合中删除原始对象,更改为您的副本,然后将副本添加到集合。

You will only be able to use const members of your class in this context, and add() is not declared const. If you want to modify the object and have those changes reflected in the set, you will have to make a copy of the object, remove the original object from the set, make the change to your copy, and then add the copy to the set.

这篇关于使用iterator在STL Set中调用非静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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