Inserting elements into 2D vector

后端 未结 3 607
遥遥无期
遥遥无期 2021-01-18 06:44

so I\'m creating a class that implements an adjacency list. Currently in my class definition I initialized two vectors:

vector> adjLi         


        
3条回答
  •  星月不相逢
    2021-01-18 06:55

    A couple of notes here.

    Your loop can be significantly shortened just be using the constructors of your two members:

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

    If you can't do this at construction time (maybe numOfValues isn't known yet), then there's still a better loop phrasing 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, by using clear and push_back to essentially build the same vector every loop iteration, you are risking an allocation and deallocation each iteration. In practice, most implementations won't do this, but if we can both shorten and potentially make things more efficient, we may as well.

    Lastly, if the number of neighbors is relatively small and similar row to row (for instance a finite elements code with tetrahedral elements, where each element connects to ~5 others), then as others have suggested you may be better off with a different structure than vector-of-vector. For instance, a single vector that is logically organized such that a new "row" begins every N elements.

提交回复
热议问题