findの使い方
まずはfindから。
string型には、もう定義されてる
#includesize_type find( const string& str, size_type index = 0 ) const; size_type find( const charT* str, size_type index = 0 ) const; size_type find( const charT* str, size_type index, size_type length ) const; size_type find( charT ch, size_type index = 0 ) const;
ここでポイントなのが、インデックス番号を返すということ.
インデックス番号を知るには、ふつうに、
cout << find(str.begin(), str.end(), item) << endl;
とすれば、OK!!
文字列を逆からたどりたいときとかはrfindを使えば良い.
string s = "10001100"; int pos = s.rfind('1'); //pos = 5 for(int i = pos; i < s.length(); i++) { cout << s[i] << endl; //1 0 0 } rfind()関数は、検索文字列を”index”から逆順に文字列を検索し、最後に見つかった位置を返します。 もし文字列が見つからないと、string::not_foundを返します。 検索位置は、文字列の最初から0から数えます。 逆順に検索を開始し、最後に現れる位置を返します。
#includeinput_iterator find( input_iterator start, input_iterator end, const T& val );
で、ポインタのごとく、扱えるイテレータが戻り値になっている.
なので、インデックス番号を求めるには、少しテクニックが必要。
vectortest; for(int i = 0; i < 10; i++) { test.push_back(i*i*i); // if(i == 4) { // test.push_back(3*3*3); //これがあっても、結果は同じ. // } } vector ::iterator it = find(test.begin(), test.end(), 27); cout << it-test.begin() << endl; //3 //0から始まって欲しいなら、-1すれば問題なし.
findは、重複する要素がある時、一番始めに出てくるイテレータおよび、インデックス番号を返す.
値が見つからなかったら、test.end()のイテレータを返す.
vector::iterator it = find(test.begin(), test.end(), 28); //28は存在しない. if(it != test.end()) { cout << it-test.begin() << endl; } else { cout << "test.end()" << endl; } }
test.end()は最後の要素の次をさすけれど、もし、その場所の値を調べてしまったらどうなるか実験.
vector::iterator it = find(test.begin(), test.end(), 28); cout << *it << endl; //0が出力される //危険なので止めた方が良い.
findの複数検索.
while((it = find(it, name.end(), q) ) != name.end()) { int p = it - name.begin(); istringstream iss(publications[pos[p]]); string s; while(iss >> s) { if(rank[s] != -1) continue; que.push(s); rank[s] = rank[q]+1; } it++; } //処理の終了時にfindのイテレータを一個先にずらさないと、whileのループが永遠に回り続けるので、注意.