Can you access elements in a vector using strings?

For example, to access a certain element in a vector of classes, you'd write:
1
2
std::vector<class1> myVector;
myVector[1].update();


but is there any way to make it look like this?
 
myVector["Player"].update();
No. But you can do that with an associative container such as a std::map or std::set.
As AbstractionAnon said, you want an associative container like std::map:
1
2
3
std::map<std::string, class1> myMap;
myMap["Player"] = class1(1, 2, 3);
myMap["Player"].update();
thanks!

is there any reason why you can't do this with a vector? or is it 'just the way it is'?
Last edited on
The difference between a vector and a map or set is that vector is indexed by an integer value (like an array). maps and sets have "keys". That key can be a string or some other object type that uniquelly identifies the entry.

There is also a difference in how vectors and sets/maps are stored. vectors are stored as a dynamically allocated array, hence the requirement for an integer index. sets and maps are generally implemented as binary (red/black) trees which allows efficient "finding" of a node by its key.

A vector stores a contiguous sequence of elements. A map stores a unique set of keys which are associated with one value each. There are times where you would use a std::map<int, blah> instead of a std::vector<blah>.
Last edited on
Topic archived. No new replies allowed.