gpt4 book ai didi

c++ - 在 vector 中搜索时出现段错误

转载 作者:行者123 更新时间:2023-11-30 05:08:16 25 4
gpt4 key购买 nike

当我尝试在 vector 中搜索特定值时遇到段错误。 vector 类型为Person

struct Person{
string name;
string address;
string email;
string number;
string SocialSec;
string other;
};

这是我的搜索功能:

void searchContact(vector<Person> &people) {
string searchTerm;
cout << endl;
cout << "Enter search term: ";
getline(cin, searchTerm);
vector<Person>::iterator it=find(people.begin(), people.end(), searchTerm);

if (it != people.end()){
cout << *it;
}else{
cout << "Element not found\n";
}
}

这里是 == 和 << 运算符的运算符重载:

ostream& operator<<(ostream &stream, const Person &it){
stream << it;
return stream;
}

bool operator==(const Person &lhs, const string &rhs){
return lhs.name == rhs;
}

这是段错误的样子:

Program received signal SIGSEGV, Segmentation fault.
0x00005555555565ae in operator<< (
stream=<error reading variable: Cannot access memory at address 0x7fffff7feff8>,
it=<error reading variable: Cannot access memory at address 0x7fffff7feff0>) at class.cpp:114
114 ostream& operator<<(ostream &stream, const Person &it){
(gdb)

回溯:

#1  0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#2 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#3 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#4 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#5 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#6 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#7 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#8 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#9 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#10 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#11 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#12 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#13 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#14 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#15 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#16 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#17 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115
#18 0x00005555555565c9 in operator<< (stream=..., it=...) at class.cpp:115

为什么会发生这种情况,我该如何解决?是不是栈溢出了?

编辑:在原始帖子中添加了 operator<< 重载以进行澄清。

最佳答案

您的运算符(operator)应该打印您的 Person 类的原始类型。像这样:

ostream& operator<<(ostream &stream, const Person &it){
stream << "This is the name: " << it.name;
return stream;
}

如果你在你的函数中做 stream << it ,它会继续尝试在无限递归调用中打印 Person 。

关于c++ - 在 vector 中搜索时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942749/

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