我正在编写一个代码,根据对象的ID相交对象的两个 vector 。我遇到运行时错误。我试图找出问题所在,但没有任何线索。你能在这里帮我吗?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Mclass
{
public:
uint64_t id;
string name;
Mclass(uint64_t _id, string _name)
{
id = _id;
name = _name;
}
bool operator<(const Mclass &info) const
{
return (this->id < info.id);
}
Mclass operator=(const Mclass &source)
{
this->id = source.id;
this->name = source.name;
return *this;
}
bool operator==(const Mclass &info) const
{
return (this->id > info.id);
}
};
int main()
{
vector <Mclass> v1;
vector <Mclass> v2;
vector <Mclass> v_in;
v1.push_back(Mclass(1, "a1"));
v1.push_back(Mclass(2, "a2"));
v1.push_back(Mclass(5, "a5"));
v2.push_back(Mclass(2, "b2"));
v2.push_back(Mclass(3, "b3"));
v2.push_back(Mclass(5, "b5"));
for(int i = 0; i < v1.size(); ++i)
{
cout << v1[i].id << ": " << v1[i].name << endl;
}
for(int i = 0; i < v2.size(); ++i)
{
cout << v2[i].id << ": " << v2[i].name << endl;
}
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v_in.begin(),
[](const Mclass& arg1, const Mclass& arg2)
{
return (arg1.id == arg2.id);
});
for(int i = 0; i < v_in.size(); ++i)
{
cout << v_in[i].id << ": " << v_in[i].name << endl;
}
return 0;
}
gdb日志
(gdb) run
Starting program: /mnt/DATA/Dropbox/ExperimentalCode/CPP/a.out
1: a1
2: a2
5: a5
2: b2
3: b3
5: b5
Program received signal SIGSEGV, Segmentation fault.
0x08049641 in Mclass::operator=(Mclass const&) ()
(gdb) bt
#0 0x08049641 in Mclass::operator=(Mclass const&) ()
#1 0x0804949a in __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > > std::set_intersection<__gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, main::{lambda(Mclass const&, Mclass const&)#1}>(__gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, __gnu_cxx::__normal_iterator<Mclass*, std::vector<Mclass, std::allocator<Mclass> > >, main::{lambda(Mclass const&, Mclass const&)#1}, main::{lambda(Mclass const&, Mclass const&)#1}) ()
#2 0x08049114 in main ()
最佳答案
您正在尝试将对象写入空 vector 。您可能打算使用
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),
std::back_inserter(v_in),
[](const Mclass& arg1, const Mclass& arg2)
{
return (arg1.id < arg2.id);
});
请注意,在输出范围中还添加了使用
std::back_inserter()
的功能。同样,正如Igor Tandetnik在评论中指出的那样,谓词必须在对象上定义严格的弱序,而不是等式关系。请注意,需要对输入进行排序(在您的示例中,创建的输入是排序的)。