2016-11-03 3 views
0

私はそれにいくつかの要素があるconst vector<string>を持っていて、そのベクトルのサブセットconstを作成したいと思います。どうすればいいですか?不変のベクトルの不変のサブベクトル

C++が以下のコードのようなものをサポートしていれば理想的ですが、残念ながらそれはありません。誰かが周りの仕事を知っていますか?

#include <fstream> 
#include <vector> 
#include <string> 
#include <iostream> 
#include <algorithm> 

using namespace std; 

int main() { 
    ifstream infile("input.txt"); // contains apple, orange, banana in separate lines 
    istream_iterator<string> eos; 
    istream_iterator<string> input(infile); 
    const vector<string> stuff(input, eos); 
    const vector<string> a_stuff(stuff.copy_if([](const string& s) { return s[0] == 'a'; })); 

    return 0; 
} 
+0

インデックスを元のベクトルに格納するには、サブベクトルを使用することは相当でしょうか? –

答えて

2

あなたはサブセットが含まれているコピーを作成したいと仮定すると、あなたが関数を使用すると、同じことを達成するためにboost::filter_iteratorを使用することも可能であるconst vector<T>

#include <vector> 
#include <algorithm> 
#include <iterator> 

template <typename T, typename Pred> 
std::vector<T> vector_copy_if(std::vector<T> const & vec, Pred && pred) 
{ 
    std::vector<T> result; 
    std::copy_if(vec.begin(), vec.end(), std::back_inserter(result), pred); 
    return result; 
} 



int main() 
{ 
    std::vector<int> const some_numbers { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
    std::vector<int> const even_numbers = vector_copy_if(some_numbers, [](int x) { return x % 2 == 0; }); 
} 
+0

それはそれにhackishの質を持っていますが、それは動作します。ありがとう。 –

1

に結果を割り当てることができます結果:

#include <vector> 
#include <string> 
#include <boost/iterator/filter_iterator.hpp> 

using namespace std; 

int main() 
{ 
    const vector<string> v {"apple", "banana", "orange"}; 
    auto filter= [] (string s){return s.length() > 0 && s[0] == 'a';}; 
    auto start = boost::make_filter_iterator(filter, v.begin(), v.end()); 
    auto end = boost::make_filter_iterator(filter, v.end(), v.end()); 
    const vector<string> cv (start, end); 
} 
+0

クールだが、残念ながらブーストを使用していない –