c++ - Using auto keyword to fill doubly-indexed vector -
trying better learn auto
keyword. i'd allocate doubly-indexed vector
using auto
keyword, when print vector (which should 0
's), instead prints empty space, in correct "shape" of vector.
mwe:
#include <iostream> #include <vector> void displayvector(const std::vector<std::vector<double> >& vec) { std::cout << "vector: \n\n"; (auto : vec) { (auto j : i) { std::cout << j << " "; } std::cout << "\n"; } std::cout << "\n"; } int main() { std::vector<std::vector<double> > vec1, vec2; /* want work */ vec1.resize(5); (auto : vec1) { i.resize(3); } displayvector(vec1); /* "old" way of doing */ vec2.resize(5); (int = 0; < 5; ++i) { vec2[i].resize(3); } displayvector(vec2); }
this results in
vector: vector: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
what proper method of doing this? 1 preferred? accepting critiques on code implementation :)
in usage, on own, auto
work values, resize copies of vectors within vec1
.
change loop vec1 use reference
for (auto &i : vec1) { i.resize(3); }
also change both loops within displayvector()
use const auto &
(a const
reference rather value). won't change output, avoid copying vectors around.
note: v154c1 , neil kirk have said same things in comments.
Comments
Post a Comment