In article <11**********************@75g2000cwc.googlegroups. com>,
ju******@gmail.com says...
When should I use each of these three containers? What is the
difference?
For list and vector, it is obvious. How about set and map?
A map has a key, and some data attached to that key. A set only has a
key, with nothing else attached to it.
A couple of examples: if you wanted to print out the words in a file,
sorted into alphabetical order, a set would make sense -- read the
words from the file into a set, then write them out from the set to
the output file.
If you wanted to store data about employees such as their name,
employee ID number, birthday, current pay rate, etc., but wanted to
support looking them up by name, a map would make sense. You'd use
the name as the key, and all the other "stuff" as the data attached
to that key.
Choosing between list and vector might not be as obvious as it
initially appears. It's true that a list supports inserting or
deleting in the middle of the list in constant time. It's also true,
however, that finding that spot in the middle of the list normally
takes linear time. Worse yet, where a vector uses contiguous storage,
a list normally uses non-contiguous storage. That can make it quite
slow to find a particular spot in the list. In a different direction,
std::list requires a doubly-linked list. A list with a lot of nodes
and only a small amount of data in each node can waste a great deal
of memory.
These are useful a lot less often than they might initially appear.
In fact, I'm pretty sure in the 10 years (or so) since I first
started using (then pre-standard) STL, I haven't run into a single
situation where I put an std::list to real use. I've had a couple
that might have been close calls, and I can _imagine_ some where
they'd make but it hasn't arisen in real use for me yet.
--
Later,
Jerry.
The universe is a figment of its own imagination.