简体   繁体   中英

Inserting multiple elements at same position in a vector

This is code for representing adjacency list using vector in C++(from geeksforgeeks).

// A utility function to add an edge in an 
// undirected graph. 
void addEdge(vector<int> adj[], int u, int v) 
{ 
    adj[u].push_back(v); 
    adj[v].push_back(u); 
} 

// A utility function to print the adjacency list 
// representation of graph 
void printGraph(vector<int> adj[], int V) 
{ 
    for (int v = 0; v < V; ++v) 
    { 
        cout << "\n Adjacency list of vertex "
             << v << "\n head "; 
        for (auto x : adj[v]) 
           cout << "-> " << x; 
        printf("\n"); 
    } 
} 

// Driver code 
int main() 
{ 
    int V = 5; 
    vector<int> adj[V]; 
    addEdge(adj, 0, 1); 
    addEdge(adj, 0, 4); 
    addEdge(adj, 1, 2); 
    addEdge(adj, 1, 3); 
    addEdge(adj, 1, 4); 
    addEdge(adj, 2, 3); 
    addEdge(adj, 3, 4); 
    printGraph(adj, V); 
    return 0; 
}

addEdge(adj,0,1) and addEdge(adj,0,4) both push_back values 1 and 4 at position 0. So my question is can we insert two or more values at same position in vector? Does it create some sort of linked list at a particular position of vector when more than one values are inserted into that position? If not, can please someone explain the working of above code.

So my question is can we insert two or more values at same position in vector

No, we can't. A vector contains exactly one element in each index. No more; no less. Just like an array.

Does it create some sort of linked list

No. Vector is implemented using a dynamic array; not a linked list.

can please someone explain the working of above code.

vector<int> adj[V] is an array of vectors. Each vector represents the adjacency list of the vertex identified by the index where the vector is stored, and each of those vectors can contain multiple elements.

You can use nested vector to insert more than one values at a position.

Declaration vector< vector<int> > adj[V];

Now to insert a value at position 0 you can use like this

void addEdge(vector<int> adj[], int u, int v, int val) 
{ 
    adj[u][v].push_back(val); 
    adj[v][u].push_back(val); 
}

To add element

addEdge(adj, 0, 0, 1); // insert 1 at position (0,0)

Please keep in mind that before adding element you need to initialize vector at every index .

But you can't insert two or more values at same position in vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM