C++中使用find查找vector内User对象的问题及实现咨询
问题分析与解决
1. 为什么需要重载==运算符?
std::find会逐个比较容器元素和目标元素是否相等,但自定义User类没有默认的相等判断规则,编译器无法识别两个User对象何时相等,因此必须手动重载==运算符,明确判断逻辑(此处为用户名和密码均相同则视为相等)。
2. 重载==运算符的实现
在User类的public区域添加以下代码:
bool operator==(const User& other) const { return username == other.username && password == other.password; }
添加const修饰符是为了保证函数不会修改当前对象,同时能接收const类型的参数,符合std::find的调用要求。
3. 代码中的核心逻辑错误修正
错误1:用户存储失效
NewUser函数中新建的StorageVector vec1是局部变量,函数执行完毕后会被销毁,新注册的用户无法保存到主函数的存储容器中。需将主函数的U1以引用方式传递给NewUser:
void NewUser(StorageVector& storage){ string username, password; cout << "-------- REGISTER NEW USER --------" << "----------------------------------" << endl; cout << "Give me the username: "; cin >> username; cout << "Give me your password: "; cin >> password; storage.UsersDatabase.push_back(User(username, password)); }
主函数调用时改为:NewUser(U1);
错误2:登录判断逻辑颠倒
if(it != U1.UsersDatabase.end())表示找到用户,但原代码输出"用户未找到",逻辑完全相反。修正后的判断逻辑:
if(it == U1.UsersDatabase.end()){ cout << "User not found! redirecting..." << endl; NewUser(U1); } else { cout << "Login successful!" << endl; }
4. 完整修正代码
users.h
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; class User{ private: string username, password; public: User(string new_username, string new_password): username(new_username), password(new_password){} // 重载==运算符 bool operator==(const User& other) const { return username == other.username && password == other.password; } }; class StorageVector{ public: vector <User> UsersDatabase; };
main.cpp
#include <iostream> #include "users.h" using namespace std; // 引用传递存储容器,保证用户数据持久化 void NewUser(StorageVector& storage){ string username, password; cout << "-------- REGISTER NEW USER --------" << "----------------------------------" << endl; cout << "Give me the username: "; cin >> username; cout << "Give me your password: "; cin >> password; storage.UsersDatabase.push_back(User(username, password)); } int main(){ StorageVector U1; string password, username; cout << " STUDENTS MANAGEMENT SYSTEM " << endl; cout << "------------------------------" << endl; cout << " LOGIN " << endl; cout << "--> Username: "; cin >> username; cout << "--> Password: "; cin >> password; auto it = find(U1.UsersDatabase.begin(), U1.UsersDatabase.end(), User(username,password) ); // 修正判断逻辑:迭代器等于end()表示未找到 if(it == U1.UsersDatabase.end()){ cout << "User not found! redirecting to register..." << endl; NewUser(U1); } else { cout << "Login successful! Welcome back." << endl; } return 0; }
5. 如何判断对象是否存在于vector中?
利用std::find的返回值即可判断:
- 若返回的迭代器等于容器的
end(),说明目标对象不存在 - 若迭代器不等于
end(),说明目标对象存在
示例逻辑:
auto it = find(vec.begin(), vec.end(), target_obj); if(it == vec.end()){ // 对象不存在 } else { // 对象存在 }
内容的提问来源于stack exchange,提问作者NachoTacos
相关产品推荐
相关产品推荐

