我正在编写一个代码,用于根据对象的id交叉两个对象向量。我收到运行时错误。我试图找出问题,但没有任何线索为什么?你能帮帮我吗?
#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 log
(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 ()
答案 0 :(得分:5)
您正在尝试将对象写入空向量。你可能想要使用
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在评论中指出的那样,谓词必须在对象上定义严格的弱顺序而不是平等关系。请注意,输入需要进行排序(在您的示例中,您创建了它们已排序)。