gpt4 book ai didi

c++ - 错误 : no matching member function for call to 'push_back'

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:34 39 4
gpt4 key购买 nike

为什么我在最后两行收到错误?目标是在集合中找到对象,并修改其内容。

using namespace std;

struct mystruct {
int id;
vector<int> y;
mystruct(const int id):id(id) {}
bool operator<(const mystruct& x) const { return id < x.id; }
bool operator==(const mystruct& x) const { return id == x.id; }
};

void test() {
std::set<mystruct> sx;
mystruct x(1);
x.y.push_back(1); x.y.push_back(2);
sx.insert(x);
//
set<mystruct>::iterator i = sx.find(1);
const mystruct* x1 = &(*i);
const mystruct x2 = *x1;
cout << &(i->y) << endl;
cout << &(x1->y) << endl;
cout << x2.id << endl;
x2.y.push_back(3);
i->y.push_back(4);
}

好像迭代器返回的是常量对象,不让我用push_back()修改 vector y。我该如何克服这个问题?

错误:

test.cpp:27:8: error: no matching member function for call to 'push_back'
x2.y.push_back(z);
~~~~~^~~~~~~~~
/opt/local/libexec/llvm-6.0/include/c++/v1/vector:688:36: note: candidate function not viable: 'this' argument has type 'const vector<int>', but method is not marked const
_LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
^
/opt/local/libexec/llvm-6.0/include/c++/v1/vector:691:36: note: candidate function not viable: 'this' argument has type 'const vector<int>', but method is not marked const
_LIBCPP_INLINE_VISIBILITY void push_back(value_type&& __x);
^

最佳答案

x2const 声明限定符,即 const mystruct x2 , C++ 编译器只考虑 const -x2 上所有调用的合格成员函数及其任何成员。特别是,它正在寻找 void push_back (const int& val) const要调用的成员函数。显然,没有这个功能,因为push_back必须修改容器,所以编译器会产生一个错误来解释到底发生了什么:

candidate function not viable: 'this' argument has type 'const vector<int>', but method is not marked const

在您的代码中解决此问题的唯一方法是删除 const来自 x2 的限定符的声明。

关于c++ - 错误 : no matching member function for call to 'push_back' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322794/

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