std::map, access key

Hi,

I have a "fairly" large, std::map.

Is there a way, to get the key of an element, by position?

e.g., something like,

map.at(i).getkey



Thanks :)

c
No, the point of a map is that the key is used as the index. Why would you use a map if you wanted to get something by it's position? Maybe you wanted a vector of pairs?
ah, got it,

1
2
3
4
for (std::map<std::string,std::string>::iterator it = queriesm.begin(); it != queriesm.end(); it++)
	{
		string = it->first;
	}
Last edited on
Yes, what I actually want is a structure, where I can access values by the key, but, the the data structure is unsorted (i.e., sorted only by order of insertion).

Does std::unordered map satisfy this?

I have also tried a std::vector<std::pair<key,value>>, but, in order to access by key, don't I MANUALLY need to iterate through the elements, until I get the correct one?
Is there a data structure that allows for DIRECT access by key, and, that is unsorted.

By direct, i mean that the structure has a "get-value-by-key" implementation. I don't care about how it does it, I.e., about time complexity, as long as it is not absolutely unreasonable", of course, but, it should obviously at max be O(n), but again, without me having to implement it myself, or having tomyself loop through the elements.
Last edited on
With unordered_map the elements will be unsorted but it does not guarantee the order the elements are stored.
Yes, what I actually want is a structure, where I can access values by the key, but, the the data structure is unsorted (i.e., sorted only by order of insertion).

Does std::unordered map satisfy this?

No. std::unordered_map is unordered. Iteration over a std::unordered_map is not in order of insertion. By the way, "sorted by order of insertion" and "unsorted" are not synonymous.


I have also tried a std::vector<std::pair<key,value>>, but, in order to access by key, don't I MANUALLY need to iterate through the elements, until I get the correct one?

A search must be performed, yes. Although, rather than doing it MANUALLY perhaps you could use std::find_if.


Search time is not a great issue here, I would just like for the data structure to have a value-by-key access implementation, regardless of time complexity

Then a vector seems appropriate.

[Edit: http://ideone.com/37AlUC ]
Last edited on
Topic archived. No new replies allowed.