GenericUser01
GenericUser01

Reputation: 457

Getting elements in an adjacency list

I have a question regarding adjacency lists. This is an example list I am using.

enter image description here

In code (C++), I am implementing this as a vector of lists of some generic element. So vector<list< element >>. In this case, the elements A, C, D, H, K, L, N are all in a vector. My question is grabbing a particular element. Say I use a for loop to iterate through the vector adjList. To get an element from a vector, you'd say *vector name*[i] and that gets the element by itself. But what does it do when the element in the vector is the beginning of a list? Let's say I only want element D. To get that I say adjList[3]. Would that grab just D? Or would saying that grab the whole list that starts at D? I don't want the whole list, I just want D. If it grabs the whole list, how would I get it to grab just the one element I want? Can someone help explain?

Upvotes: 0

Views: 275

Answers (1)

Honza Remeš
Honza Remeš

Reputation: 1193

As you write yourself, you have a vector<list< element >>. That means that adjList[i] will give you a list. Your A,C,D elements are accessed as adjList[i].front(), or verbosely,

list< element > l = adjList[i];
element D = l.front();

The latter may be useful if you'll need to work with the rest of the list too.

Upvotes: 1

Related Questions