C++: シーケンスが別のシーケンスを含んでいるかテストする
<algorithm> std::search の簡単なラッパー。
主な用途は string と vector。
#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 件のコメント:
コメントを投稿