Reputation: 590
I declared a vector of linked list (and the linked lists hold int
values). Then I tried to push a value onto the linked list (i
is just a position in the vector):
vector< list<int> > linkedListVector;
adjacencyVector[i].push_back(s);
The problem is that I run into a segmentation fault when I run the above command and I don't know why. I looked up the C++ documentation and my formatting looks correct. Any ideas?
Upvotes: 1
Views: 11092
Reputation: 1294
Then I tried to push a value onto the linked list.
You tried to access an object, which didn't exist. The adjacencyVector[i] list does not exist as adjacencyVector is an empty vector if you did not put an element into it.
The following example will make some details clear.
#include <iostream>
#include <vector>
#include <list>
int main()
{
std::vector<std::list<int> > v; // This statement creates an empty vector of lists of integers.
std::list<int> l; // This statement creates an empty list of integers.
for(int i=0; i<10; ++i){
l.push_back(i);
v.push_back(l);
}
for(unsigned int i=0; i<v.size(); ++i){ // You can access elements calling the operator[].
for(std::list<int>::iterator it=v[i].begin(); it!=v[i].end(); ++it){
std::cout<<*it<<' '; // You can access elements calling the operator[] , you need an iterator.
}
std::cout<<std::endl;
}
//std::cout<<*(v[v.size()].begin())<<std::endl; // It causes segmentation fault, because v[10] does not exist,
// 10 is out of range of valid indexes.
}
Vectors and lists are quit similar. Inserting and deleting are more effective if you use list, but accessing an element is usually more effective if you use vector.
Upvotes: 0
Reputation:
If you are using a for loop then you probably already know what the max size will be so you can just use the resize
method like this:
adjacencyVector.resize(MAXSIZE)
Upvotes: 0
Reputation: 5083
The vector starts out with a size of zero, and you must create the vector element before pushing onto the list at [i]
.
If your i
progresses in a normal fashion, you could push_back()
onto the vector first, then onto the list in the vector. If not you could add something a bit ugly such as:
if ( adjacencyVector.size() <= i ) { adjacencyVector.resize(i + 1) ; }
adjacencyVector[i].push_back(s);
Upvotes: 2
Reputation: 595896
You have to add an instance of list<int>
to the vector
before you can then access a specific list<int>
by index, then you can call push_back()
on the list<int>
. So either push_back()
a list<int>
into the vector:
vector< list<int> > adjacencyVector;
list<int> l;
adjacencyVector.push_back(l);
...
adjacencyVector[0].push_back(s);
Or call the vector's resize()
method to add multiple lists at one time:
vector< list<int> > adjacencyVector;
adjacencyVector.resize(number of lists);
...
adjacencyVector[index].push_back(s);
Upvotes: 2