Yourik
Yourik

Reputation: 39

Initializing const vector with index-dependent function on other vector

in C++14, is it possible somehow to initialize a const vector using another vector of the same type, while possibly also doing element-dependent operations?

That is, I would like something like this:

const vector<double> vec1 = {1.0, 3.0, 4.0, 5.0};
vector<double> vec2(4);
for (int i = 0; i < 4; i++) {
    vec2[i] = vec1[i] * 3 + i;
}

or some other i-dependent operation, but vec2 should be const as well.

Upvotes: 1

Views: 72

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275740

Just because I find writing generic code amusing:

template<class F, class C>
C indexed_transform( C in, F&& f ) {
  for (size_t i = 0; i < in.size(); ++i) {
    in[i] = f(i, in[i]);
  }
  return in;
}

const vector<double> vec1 = {1.0, 3.0, 4.0, 5.0};

const std::vector<double> vec2 = indexed_transform(vec1,
  [](size_t i, double d){
    return d*3+i;
  }
);

also works with std::string, std::array (somewhat inefficiently), std::deque, and any random-access container. On random-access ranges, it modifies its incoming argument (and returns it).

Upvotes: 0

Barry
Barry

Reputation: 303357

Of course:

std::vector<double> foo(const std::vector<double>& v) { ... }

const std::vector<double> vec2 = foo(vec1);

Upvotes: 2

Related Questions