比较两个向量以获得公共元素/定义user1和user2
Comparing two vectors to get common elements/defining user1 and user2
我有一个私人用户的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++文档。
相关文章:
- 如何绘制自定义形状的元素?
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 从自定义类获取对象向量中的 max 元素
- 如何访问宏中定义的数组元素
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 从自定义数据类型向量中删除重复元素
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何使用某些因素的函数元素定义数组 m 由 n
- 比较两个向量以获得公共元素/定义user1和user2
- 我可以为我的自定义Qt UI元素定义自定义CSS/QSS属性吗?
- 枚举元素定义
- C++类元素定义之类的数组
- 如何将元素定义为与随机访问迭代器指向的元素相同的类型
- 使用结构的特定字符串元素定义无序映射键
- C++ 我知道数组长度,但想知道是否是一种更简洁的数组元素定义方法