How do I push vectors by reference?

  • A+
Category:Languages

This code below doesn't work because I push_back the vectors a and b to the vector vector and then alter the vectors a and b. I want to alter the vectors a and b so that the vector vector suffers the same modifications. How do I do this?

#include <iostream> #include <vector>  int main() { std::vector<std::vector<int>>vector; std::vector<int>a; std::vector<int>b; vector.push_back(a); vector.push_back(b); for (int i = 1; i <= 10; i++)     a.push_back(i); for (int i = 11; i <= 20; i++)     b.push_back(i); std::cout << vector[1][0]; std::cin.get(); } 

 


Create v (vector is not a good name since it shares with the library and makes the code confusing) to be a vector of vector pointers (since a vector of references is not possible):

std::vector<std::vector<int> *> v; //declare as vec of vec pointers ... v.push_back(&a); //push_back addresses of a and b v.push_back(&b); ... std::cout << v.at(1)->at(0) //dereference and call at on the inner vec 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: