简体   繁体   中英

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. how do i find common friends(in friend_set) for two users and output the result.

here's my code so far:

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;

   }
      }

i want to write a method called commonfriends() that finds the common friends for any given two users.

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() . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM