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.
source share