gpt4 book ai didi

c++ - 修改集合元素

转载 作者:行者123 更新时间:2023-11-30 04:13:40 26 4
gpt4 key购买 nike

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

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

我做错了什么?

#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>]’

最佳答案

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

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

关于c++ - 修改集合元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com