簡體   English   中英

在列表中查找通用元素c ++

[英]finding common elements in a list c++

有人可以舉例說明如何做到這一點。 我有一個對象的字符串friends_set,其中所有數據(即名稱,年齡,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()的方法,該方法為任何給定的兩個用戶查找共同的朋友。

最簡單的方法是使用合適的容器(可能是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM