vector中の特定の条件を満たす要素のインデックスだけを抽出
vector中の特定の条件を満たす要素だけを抽出 - My Life as a Mock Quantで要素自身を抜いていたけど、
これが大きいオブジェクトだったらコピーコストが凄い事にと思うと夜も眠れないので、インデックスだけ抜くようにした…ら…ば…結構めんどい書き方になった。
何方かもっといいやり方教えてください。
#include<iostream> #include<vector> #include<algorithm> #include <functional> int main() { //テストデータ std::vector<int> x,y; x.push_back(1); x.push_back(3); x.push_back(4); x.push_back(5); x.push_back(3); //条件用Functor struct IsNotThree : public std::unary_function<int, bool> { bool operator()(int x) const{return x!=3;} }; //インデックス抽出 std::vector<int>::iterator it = std::find_if(x.begin(), x.end(), IsNotThree()); while (it != x.end()) { y.push_back(std::distance(x.begin(), it)); it = std::find_if(++it, x.end(), IsNotThree()); } //表示 struct Show{void operator()(int x){std::cout << x << std::endl;}}; std::for_each(y.begin(), y.end(), Show()); return 0; }
実行結果
0 2 3