Re: std::vector construction
mlt wrote:
Is there someway to create a std::vector from a sequence of numbers? On this
page:
http://www.cppreference.com/wiki/stl/vector/vector_constructors
there are 4 different constructors, but none of them supports something
like:
std::vector<int> v = {1,2,3};
Its only possible to do it like:
std::vector<int> v;
v.push_back(1,2,3);
AFAIK you can't do that by constructor. You could however use generate()
or generate_n() algorythm in <algorithm> head file and fill empty vector
with values generated by Generator. You however, need, generator :P
Something like this
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
class Gen { // generator
private:
int value;
int step;
public:
Gen(int bb = 0, int ss = 1) : value(bb), step(ss) {}
int operator()() {
int old = value;
value += step;
return old;
}
};
int main() {
vector<int> v1;
generate_n(back_inserter(v1), 50, Gen(1,1));
vector<int> v2(50);
generate(v2.begin(), v2.end(), Gen(0,5));
for(int i=0; i<v1.size(); i++) {
cout << v1[i] << " ";
}
cout << endl;
for(int i=0; i<v2.size(); i++) {
cout << v2[i] << " ";
}
cout << endl;
}
Hopefuly it helped.