Insert Elements into a 2D Vector

so I create a class that implements an adjacency list. Currently, in the definition of my class, I have initialized two vectors:

vector<vector<int>> adjList; vector<int> neighbors; 

and I declared two functions that I plan to use for this:

 bool constructAdjList(); bool insertIntoAdjList(int, int); 

It becomes difficult to wrap my head around 2D vectors. I understand that this is essentially a vector of vectors, but I am confused about how to insert a new value into one of the "subvectors". For example, I can create an adjacency list in createAdjList, which 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 is the value 5 for the 4th vector in adjList, which will be represented in my insertIntoAdjList function as

 insertIntoAdjList(4, 5); 

I know that I can access a specific value in a 2D vector by saying adjList [4] [1], but how can I click on it?

Thanks!

+6
source share
2 answers

To click on a vector that is an element of another vector, you just do it

 adjList[x].push_back(); 
+10
source

A few notes here.

Your loop can be greatly reduced, just use the constructors of your two members:

 vector<int> neighbors(1, 0); // set to length 1, value is zero vector<vector<int>> adjList(numOfValues,neighbors); // "outer" vector is numOfValues long . // each row is a *COPY* of neighbor 

If you cannot do this during construction (perhaps numOfValues ​​is not yet known), then there is an even better loop phrase that we can use:

 // neighbors object can be reused neighbors.clear(0); neighbors.push_back(0); adjList.reserve(numOfValues); // reserving memory ahead of time will prevent allocations for (int i = 0; i < numOfValues; i++){ adjList.push_back(neighbors); // push_back is by *COPY* } 

In your example, using clear and push_back to essentially build the same vector at each iteration of the loop, you risk distributing and freeing each iteration. In practice, most implementations will not do this, but if we can both reduce and potentially make things more efficient, we can.

Finally, if the number of neighbors is relatively small and looks like a line in a line (for example, finite element code with tetrahedral elements, where each element connects to ~ 5 others), then others suggested that you might be better off with a different structure than the vector -vector. For example, one vector that is logically organized so that a new β€œline” begins with each N elements.

+1
source

Source: https://habr.com/ru/post/978972/


All Articles