[英]finding common elements in a list c++
有人可以举例说明如何做到这一点。 我有一个对象的字符串friends_set,其中所有数据(即名称,年龄,friends_set)都发送到一个.txt文件。 如何找到两个用户的共同朋友(在friend_set中)并输出结果。
到目前为止,这是我的代码:
#include "User.h"
#include<iostream>
#include <stdlib.h>
#include <iomanip>
#include<fstream>
using namespace std;
using namespace std;
int addUser();
int addUser()
{
ofstream thefile;
thefile.open("users.txt", ios::app);
string firstname;
string lastname;
int age;
string friend_set;
cout<<"Enter your First Name: ";
cin>>firstname;
thefile << firstname << ' ';
cout<<"Enter your Last Name: ";
cin>>lastname;
thefile << lastname << ",";
cout<<"Enter your Age: ";
cin>>age;
thefile << age<< ",";
cout<<"Enter name of friends: ";
cin>>friend_set;
thefile << friend_set << endl;
thefile.close();
cout<<"User Added."<<endl;
return 0;
while (cin >> firstname >> lastname >> age >> friend_set) {
thefile << firstname << ' ' << lastname << "," << age << "," << friend_set << endl;
}
}
我想编写一个名为commonfriends()的方法,该方法为任何给定的两个用户查找共同的朋友。
最简单的方法是使用合适的容器(可能是std::vector<std::string>
表示一组朋友,并确保对该容器进行排序(例如,使用std::sort()
。 如果要查找两个排序序列中元素的重叠,可以使用std::set_intersection()
,它将把两个集合之间的交集写入迭代器。 结果迭代器可以引用目标容器(使用std::back_inserter()
),直接写入输出流(使用std::ostream_iterator<std::string>
)或使用输出迭代器可以写入的任何其他目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.