C++: シーケンスが別のシーケンスを含んでいるかテストする
<algorithm> std::search の簡単なラッパー。
主な用途は string と vector。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <iostream> #include <vector> #include <algorithm> template < typename T> bool contains(T const & a, T const & b){ return std::search(a.begin(),a.end(),b.begin(),b.end())!=a.end();} using namespace std; int main( int argc, char **argv) { cout << contains(string( "abcdefg" ), string( "efg" )) << endl; // true cout << contains(string( "abcdefg" ), string( "efh" )) << endl; // false cout << contains(string( "abcdefg" ), string( "" )) << endl; // true cout << contains(string( "" ), string( "efg" )) << endl; // false cout << contains(string( "efg" ), string( "efg" )) << endl; // true cout << contains(string( "" ), string( "" )) << endl; // false int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 1, 2 }; int z[] = { 1, 2, 5 }; vector<vector< int > > seq; seq.push_back(vector< int >(x, x + sizeof (x) / sizeof (x[0]))); seq.push_back(vector< int >(y, y + sizeof (y) / sizeof (y[0]))); seq.push_back(vector< int >(z, z + sizeof (z) / sizeof (z[0]))); for ( int i = 0; i < 3; ++i) { for ( int j = 0; j < 3; ++j) { cout << contains(seq[i], seq[j]) << " " ; } cout << endl; } // true true false // false true false // false true true } |
0 件のコメント:
コメントを投稿