c++ - 比较两个 vector 以获得公共(public)元素/定义 user1 和 user2

标签 c++ visual-c++ object vector stdvector

我有一个包含私有(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/

相关文章:

c++ - 为什么boost::locale::date_time中的std::bad_cast异常适用于全局而不是本地对象?

c++ - 内存与无理数与 float

c++ - 动态创建的自定义 QML 对象不可见

c++ - 如何在 C++ 中将字符串转换为 char *?

javascript - 使用变量 angularjs 访问嵌套对象

c++ - const_iterator<T> 和 iterator<const T> 有什么区别?

c - `va_num` 在这个可变参数宏中意味着什么?

c++ - 使用 C++ 的 OpenGL 中的动画点?

java - java中使用(Class)对象会恢复对象吗?

javascript - 对象的属性访问和普通变量访问之间的速度差异是多少?