Hello.. Im new to stl..
Whats the best way to find data in the list by the string?
Hello.. Im new to stl..
Whats the best way to find data in the list by the string?
Last edited by l2u; 09-05-2006 at 01:56 PM.
It depends. If you will have a lot of data and be doing a lot of lookups by the string, you should use a map or a set instead of a vector or list. The set and map classes are also standard library containers, so you shouldn't have too much trouble learning them. What they provide is logarithmic time lookup, which is much faster than linear that a list would use.
Another option if you are using a vector, and all your objects will be added in the very beginning, is to add the objects first, then sort the vector using std::sort, and then use std::binary_search to find the data.
If, however, you only have a few items to store, then a linear search is fine. The best way to do this is to use the list.find() method, or if you are using a vector use the std::find algorithm.
Hey Daved, you're very helpful.. Can I use vector inside the map?
Yes you can, although in general you'll want to use a std::vector only as the data, not the key.
Something like this: std::map<std::string, std::vector<std::string> >
is a map that looks up based on a string key, and has a vector of strings as the data.
(You NEED a space between the last two > > or it will think it's supposed to be the operator >>).
You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.
that's one of the nasty 'gotcha's of C++. when creating containers of containers, I prefer to use something likeOriginally Posted by Catjust to be on the safe sideCode:typedef std::vector<std::string> vec_string; std::map< std::string, vec_string > my_map;
Why would that be more safe?Originally Posted by Bench82
Bench82 is just referring to the fact that you have to put a space between the two > characters, so using the typedef just means you won't need to put two > characters together and so you won't forget to put the space. It doesn't actually make the code safer from run-time errors.
BTW, that will be fixed in the next standard, so at some point soon compilers will allow the >> without the space.
The map only supports two types of data, am I right with that?
It depends on what you mean. A map holds a key-value pair. You can use whatever type you want for the key as long as you make it sortable if it isn't already. So an int, double, string or instance of your own class that implements operator< are all examples of valid key types. You then use whatever type you want for the value, as long as it is copyable. Again, the examples above for keys would also work as values. A vector would also work as a value.
If you have multiple datatypes that you want to store as the value, you generally combine them into a struct or class and then use the class as the value type.