比较两个向量以获得公共元素/定义user1和user2

Comparing two vectors to get common elements/defining user1 and user2

本文关键字:元素 定义 user2 user1 两个 向量 比较      更新时间:2023-10-16

我有一个私人用户的User类,用于个性化用户的配置文件,例如姓名、年龄、收藏夹。我想比较两个给定用户的收藏夹,并输出共同的收藏夹。由于我将使用向量,我的问题是如何将用户分组到向量(user1,user2),以便比较任何给定成员的收藏夹并输出结果。这就是我目前拥有的

user.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>库,假设您可以对向量进行排序:

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));

首先来看一下。我不相信你需要使用向量。我倾向于使用deque或list,除非有某种原因需要数据元素在内存中是连续的。http://www.cplusplus.com/reference/algorithm/set_intersection/http://www.cplusplus.com/reference/deque/

我建议您使用该函数的另一个版本,这样您就可以设计一个函子来处理比较。您可能需要为用户定义结构。

struct user
{
   std::string firstname;
   std::string lastname;
   int age;
   std::deque<std::string> favorites;
}
std::deque<user> users[X];  // Define the constant X somewhere depending on number of users

你问的是一个设计问题,很明显,答案可能会一直持续下去。这取决于你如何使用构建块来设计你的程序。根据你到目前为止所做的工作,我并不清楚收藏夹可能是什么。你必须定义一个表示每个用户的结构,以及一个可以按照你想要的方式比较两个用户对象的比较函数或静态函数。可能有很多方法可以做到这一点。这些只是一些想法。为了学习如何使用这些东西,您必须阅读一些C++文档。