Reputation: 312
As far as I looked through the C++ reference, there is no function which returns a vector (or similar) containing all the keywords of a map. Why is this so? This is not a super important function, but sometimes it can be useful. (I don't exactly understand the key_comp function, but this seems to be not what I'm looking for)
Just for completeness, here is some function which does what I want:
template<typename key_t, typename value_t>
std::vector<key_t> getKeywords(const std::map<key_t, value_t>& m){
std::vector<key_t> keywords;
for(const auto& it: m){
keywords.push_back(it.first);
}
return keywords;
}
Upvotes: 1
Views: 260
Reputation: 385174
This is for the same reason that there is no operator+
for std::list
iterators.
The standard tries not to encourage inefficient operations, in preference for you choosing the appropriate container for the job.
Creating a vector of all map keys is non-trivial because such a vector is not maintained internally along with the map.
You can of course create it if you really want, as you've already shown. But the standard wants you to know that you probably should be looking for another approach.
For example, if you just want to iterate over the keys, you can iterate over the whole map instead and use only the first part of each resultant pair.
Also, the standard library is intended to give you building blocks, not to suit every possible use case imaginable.
Upvotes: 4
Reputation: 41509
Indeed, the keys
are not accessible as such because the concern of the map
class is O(log(N)) retrieval, not iteration.
As a general guideline when using the stl, choose your containers according to the use case of your application. If you want fast iteration, you can use a vector
of tuple<Key, Value>
and sort it, or use a pair<vector<Key>, vector<Value>>
that you keep sorted by hand. std::make_heap
and the like can be handy for this approach.
Retrieving the map keys can be done like your implementation.
Upvotes: 1
Reputation: 179839
The two chief reasons are that most implementations do not have a vector of keywords intenally, so they would have to create it on the fly. And as you can see, creating it isn't really hard so there is little need to have it in the Standard,
Upvotes: 2