在列表c ++中查找公共元素

时间:2013-11-30 17:14:56

标签: c++ visual-studio

有人可以通过一个例子解释如何做到这一点。我有一个对象的字符串friends_set,其中所有数据(即name,age,friends_set)都被发送到.txt文件。如何为两个用户找到共同的朋友(在friend_set中)并输出结果。

到目前为止,这是我的代码:

user.cpp

   #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()的方法,找到任何给定两个用户的共同朋友。

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用合适的容器(可能是std::vector<std::string>)来表示朋友集,并确保对此容器进行排序,例如使用std::sort()。如果要在两个排序的序列中找到元素的重叠,可以使用std::set_intersection(),它将两个集合之间的交集写入迭代器。结果迭代器可以引用目标容器(使用std::back_inserter()),直接写入输出流(使用std::ostream_iterator<std::string>),或使用输出迭代器可以写入的任何其他目标。