[英]finding common elements in a list c++
can someone please explain how to do this with an example. 有人可以举例说明如何做到这一点。 i have string friends_set for an object, where all data(ie name,age, friends_set) is sent to a .txt file.
我有一个对象的字符串friends_set,其中所有数据(即名称,年龄,friends_set)都发送到一个.txt文件。 how do i find common friends(in friend_set) for two users and output the result.
如何找到两个用户的共同朋友(在friend_set中)并输出结果。
here's my code so far: 到目前为止,这是我的代码:
#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;
}
}
i want to write a method called commonfriends() that finds the common friends for any given two users. 我想编写一个名为commonfriends()的方法,该方法为任何给定的两个用户查找共同的朋友。
The easiest approach is to represent the set of friends using a suitable container, probably a std::vector<std::string>
and make sure that this container is sorted, eg, using std::sort()
. 最简单的方法是使用合适的容器(可能是
std::vector<std::string>
表示一组朋友,并确保对该容器进行排序(例如,使用std::sort()
。 If you want to find the overlap of elements in two sorted sequences you can use std::set_intersection()
which will write the intersection between the two set to an iterator. 如果要查找两个排序序列中元素的重叠,可以使用
std::set_intersection()
,它将把两个集合之间的交集写入迭代器。 The result iterator can either reference a target container (using std::back_inserter()
), write directly to an output stream (using std::ostream_iterator<std::string>
), or use any other destination an output iterator can write to. 结果迭代器可以引用目标容器(使用
std::back_inserter()
),直接写入输出流(使用std::ostream_iterator<std::string>
)或使用输出迭代器可以写入的任何其他目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.