Mustafa Ozturk Mustafa Ozturk - 1 year ago 118
C++ Question

Immutable sub vector of immutable vector

Let's say I have one

const vector<string>
with some elements in it and I'd like to create a
subset of that vector, how can I do that?

Ideally it would be cool if C++ supported something like the code below, unfortunately it doesn't. Anybody know of a work around?

#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;

Answer Source

Assuming you want to make a copy that contains the subset, you can use a function and assign the result to a 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; });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download