4

ベクトルには複数のデータが含まれているため、ベクトルの検索関数を定義しようとしています。それは構造体のベクトルです

ID を入力して、それをテーブルで検索し、そのインデックスを見つけようとしています (その ID が既に存在する場合)。

だから私はここに宣言があります:

vector<Employee> Table;
vector<Employee>::iterator It;
vector<Employee>::iterator find_It;

//Table has these values
//Table.ID, Table.ch1, Table.ch2

そして、私はここでIDを見つけようとしています:

cin >> update_ID;
find_It = find(Table.begin(), Table.end(), update_ID);

変数 update_ID で検索を行う方法はありますか?

私はこれをやってみました:

find_It = find(Table.begin(), Table.end(), (*It).update_ID;

しかし、明らかに私のベクトル従業員には update_ID という名前のデータメンバーがありません

私が考えていたもう1つのオプションは、独自の検索機能を作成することです。これは、定義方法について少し混乱しています

Table.ID = update_ID の ID のインデックスを返したい

戻り値の型と値のパラメーターには何を指定すればよいですか? それは...ですか

returntype find( Iterator, Iterator, update ID)
{ 
    for (vector<Employee>::iterator myit = Table.begin(), Table.end(), myit++)
    {
        if update_ID == Table.ID
        {
            return myit;
        }
    }
    return myit
}
4

4 に答える 4

5

C++ 標準ライブラリには、一連の検索関数が付属しています。

find_if比較を指定するファンクターを取るものを探しています。

// a functor taking the update_ID you 
// are looking for as an argument in the constructor
struct myfind {
  myfind(int needle) : needle(needle) {}

  int needle;
  bool operator()(const Employee& x) {
    return x.ID == needle;
  }
};

// use as
int update_ID = 23;
std::find_if(begin(Table), end(Table), myfind(update_ID));

ラムダを使用することもできます:

int id;
std::find_if(begin(Table), end(Table),
             [=](const Employee& x) { return x.update_ID == id; });
于 2012-12-05T23:43:43.600 に答える
3

明らかなアプローチはstd::find_if()、述語を使用することです。C++ 2011 表記を使用すると、次のようになります。

std::vector<Employee>::iterator it(std::find_if(Table.begin(), Table.end(),
                                   [=](Employee const& e) { return e.ID == update_ID; });

C++ 2011 を使用できない場合は、述語の関数オブジェクトを作成するか、update_ID.

于 2012-12-05T23:43:43.367 に答える
3

あなたはstd::find_if() それがどのように機能するかを知ることができます

于 2012-12-06T00:05:08.993 に答える
2

find_ifを使用して、独自のマッチング関数を使用できます。最初のスニペットでは、Table ではなく、メンバー ID、ch1、ch2 を持つ Employee を参照していると思います。問題を解決する 1 つの方法は次のとおりです。

#include <vector>
#include<iostream>
#include<algorithm>

using std::cout;
using std::endl;
using std::vector;

struct Employee{
   int ID;
   int ch1;
   int ch2;
};

int IDmatch;

bool match_id( Employee myemp){
   return myemp.ID==IDmatch;
}

int main(){

   vector<Employee> Table;

   // fill example vector
   Employee temp; // use this for inserting structs into your vector
   for(int i=0; i<10; i++){
      temp.ID = i; // 1,2,3,...
      temp.ch1 = 10*i+1; // 11,21,32,...
      temp.ch2 = 10*i+2; // 12,22,32,...
      Table.push_back(temp);
   }

   vector<Employee>::iterator itv;
   IDmatch = 3;
   itv = find_if(Table.begin(), Table.end(), match_id);
   cout << "found an Employee with ID=" << IDmatch << ": ch1=" << itv->ch1 << ", ch2=" << itv->ch2 << endl;

}
于 2012-12-06T00:05:25.980 に答える