我有一个包含私有(private)用户的用户类,用于个性化用户的个人资料,例如姓名、年龄、收藏夹。我想比较两个给定用户的收藏夹并输出共同的收藏夹。因为我将为此使用 vector ,所以我的问题是如何将用户分组到 vector (user1,user2) 以便我可以比较任何给定成员的收藏夹并输出结果。这是我目前所拥有的
用户.cpp
using namespace std;
vector<string> user;
int adduser();
int adduser()
{
ofstream thefile;
thefile.open("users.txt", ios::app);
string firstname;
string lastname;
int age;
string favourites;
cout<<"Enter your Name: ";
cin>>name;
thefile << name << ' ';
cout<<"Enter your age: ";
cin>>age;
thefile << age << ",";
cout<<"Enter your favourites: ";
cin>>favourites;
thefile << favourites<< ",";
thefile.close();
cout<<" Completed."<<endl;
return 0;
}
common favourites()
{
//how do make it so i have something like user1 and user2
//which are both vectors so when i enter the name of
//user1 and user2 i can compare thier favourites and output the common ones
}
最佳答案
您可以使用 <algorithms>
库,假设您可以对 vector 进行排序:
std::sort(user1.begin(), user1.end());
std::sort(user2.begin(), user2.end());
std::vector<string> common;
std::set_intersection(user1.begin(), user1.end(), user2.begin(), user2.end(), std::back_inserter(common));
关于c++ - 比较两个 vector 以获得公共(public)元素/定义 user1 和 user2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20388767/