0

Is there someone here who can use a for loop for vectors?

I have a vector with 5 elements inside. vector <double> v (5). I would like to say that each element has a value of 1.2. Is it possible to say for (auto& element : v) { element = 1.2} ?

17th Sep 2016, 2:42 PM
MARINA
MARINA - avatar
4 Answers
+ 2
why not? or vector<double> v(5, 1.2);
17th Sep 2016, 2:49 PM
kiwiyou
kiwiyou - avatar
+ 2
Both works. vector<double> v(5); //this works: for (auto& element : v) { element = 1.2; } //this also works: v = vector<double>(5, 1.2); //yet another alternative int i; for(i = 0; i < 5; i++){ v[i] = 1.2; } //a last one (requires <algorithm>) fill(v.begin(), v.end(), 1.2); //printing the vector vector<double>::iterator it = v.begin(); while (it != v.end()) { cout << *it << endl; it++; }
17th Sep 2016, 3:17 PM
Zen
Zen - avatar
0
Or maybe I have to say tab = vector <double>(tab.size (), 1.2); ?
17th Sep 2016, 2:44 PM
MARINA
MARINA - avatar
0
Thanks! Another question when should I use vector more than an array? Because I can see anything in Solo Learn courses about vectors...
17th Sep 2016, 3:21 PM
MARINA
MARINA - avatar