STL vector, STL list, new, delete question

Hello! I have two for loops below.

The first for loop puts node objects into a vector.

The second for loop uses the delete operator to free memory created by the new operator for each node object that was put in the vector.

My question is why do I get a compile error if nodeList; is a list<Node*> instead of a vector<Node*>?

Works fine as a vector but as a list I get this error:
1>: error C2676: binary '[' : 'std::list<_Ty>' does not define this operator or a conversion to a type acceptable to the predefined operator

on this line : delete nodeList[i];


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "Node.h"
#include <iostream>
#include <list>
#include <vector>
using namespace std;
...
for(unsigned int i = 0; i < charByte.size(); i++)//putting the data into a node and the node into a list
	{
		nodeList.push_back(new Node(charByte[i], frequency[i]));
	}

	for(unsigned int i = 0; i < nodeList.size(); i++)//destroy list of nodes
	{
		delete nodeList[i];
	}
Last edited on
An STL list does not support random-access; meaning that there is no operator[] defined. You can, however, traverse the list using an iterator.

1
2
3
4
5
6
7
list<Node*> nodeList;
//...
for( list<Node*>::iterator i = nodeList.begin(); i != nodeList.end(); ++i )
{
    // i is an iterator to a Node*, dereferencing the iterator returns the Node*
    delete *i;
}


EDIT: I guess I'll add the "why" part. vector's store their elements sequentially. Internally, that means that accessing yourvector[offset] is as simple as pointing to the beginning of yourvector + sizeof(elementtype)*offset. This can be found efficiently and is implemented with operator[]. (Note that it may not be implemented exactly as I am describing, but it is safe to think of it in these terms; the user need not understand the implementation details, just the interface)

A list, is a linked list (doubly-linked, actually) meaning that each element has a pointer to a completely different memory address where the next element resides. Given the first element and a numeric offset, there is no way to go straight to the (10th, for example) offset element. The only way to get there is to linearly traverse the next element pointers; which is not so efficient. The designers of the library decided to let you do it yourself, rather than giving you a false sense of efficiency, so to speak. It's actually clever: as if they suspect that if you need random-access then you might not want to use a list.

A deque is another random-access container that you may want to look up.

I hope that helps.
Last edited on
Cool! Thanks!
Topic archived. No new replies allowed.