修改集元素

时间:2013-10-11 06:05:37

标签: c++ object set

使用下面的代码,我试图更新集合中的值,但是当我尝试编译时它没有编译。

它在底部给我错误,你能帮忙吗?

我在这里做错了什么?

#include < iostream >
#include < set >

using namespace std;

class A
{
    public:

    int a,b;

    bool operator()(A a1,A a2)
    {
        return true; 
    }

    A(int a ,int b)
    {
        this.a=a;

        this.b=b;
    }

};

void print_set(const std::set<A>&st) const
{
    std::set<A>::iterator it;
    std::cout<<"\nvalues in set";   

    for(it=st.begin();it!=st.end();it++)    
    {
        std::cout<<"\na="<<it->a<<"b="<<it->b;
    }  
}


int main ()
{
    std::set<A> s;

    for ( int i=0;i<5;i++)
    {
        s.insert(A(i,i+1));
    }

    print_set(s);

    std::set<A>::iterator it;

    for(it=s.begin();it!=s.end();it++)
    {
        A tmp=*it;

       s.erase(it);
       tmp.a=10;
       tmp.b=20;
       s.insert(tmp);

       std::cout<<"\ninserting tmp "<<tmp.a<<" "<<tmp.b;
    }

    print_set(s);

    return 0;
 }

我收到这样的错误:

/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = A]’:
/usr/include/c++/4.6/bits/stl_tree.h:1277:4:   instantiated from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = A, _Val = A, _KeyOfValue = std::_Identity<A>, _Compare = std::less<A>, _Alloc = std::allocator<A>]’

1 个答案:

答案 0 :(得分:2)

您的代码中存在一些问题,请参阅以下评论:

A(int a ,int b)
{
    //this.a=a;
    //this.b=b;
    this->a = a; // this pointer should be accessed by this->
    this->b = b;
}

// to store element in std::set, it must follow strict weak ordering rule. 
// by default, operator< need to be defined
bool operator<(const A& lhs, const A& rhs)
{
    return lhs.a < rhs.a;
}

// print_set is not a member function, can't have trailing const after function name
void print_set(const std::set<A>&st) // const