Quick Q: How do I add elements to a 2D vector of ints?--StackOverflow
Quick A: Index into the desired sub-vector
and call push_back
.
Recently on SO:
Inserting elements into 2D vector
So I'm creating a class that implements an adjacency list. Currently in my class definition I initialized two vectors:
vector<vector<int>> adjList; vector<int> neighbors;and I declared two functions that I plan to use to make it:
bool constructAdjList(); bool insertIntoAdjList(int, int);It's getting difficult wrapping my head around 2D vectors. I understand that it is essentially a vector of vectors, but I'm confused about how to insert a new value into one of the "subvectors". For example, I am able to create an adjacency list in
createAdjList
that is empty with the following loop:for (int i = 0; i < numOfValues; i++){ neighbors.push_back(0); adjList.push_back(neighbors); neighbors.clear(); }But how can I say,
push_back
the value 5 to the 4th vector inadjList
, which would be represented in myinsertIntoAdjList
function asinsertIntoAdjList(4, 5);I know I can access a specific value in a 2D vector by saying
adjList[4][1]
, but how can I push one onto it?Thanks!