91

I'm using map in C++. Suppose I have 10 values in the map and I want only the first one. How do I get it?

Thanks.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
adir
  • 1,257
  • 2
  • 16
  • 22

5 Answers5

137

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

Benoit
  • 76,634
  • 23
  • 210
  • 236
  • 1
    `myMap.begin()` returns an iterator. You might want to check http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – MSalters Jan 28 '11 at 09:00
  • 13
    No, it returns values. `myMap.begin()` is an iterator, which has the `*` and `->` operators overloaded to behave like a pointer and the `++` and `--` operators overloaded to iterate elements in your map. You should read an introduction about the STL. Maybe someone has a good link for you? – Benoit Jan 28 '11 at 09:00
  • and if i want the value and not the iterator? – adir Jan 28 '11 at 09:03
  • 2
    @adir: it's explained in the last paragraph. – jweyrich Jan 28 '11 at 09:05
  • @Benoit Do you have any idea about the type of first ,second in map? Thanks – RaHuL May 21 '20 at 12:54
20

As simple as:

your_map.begin()->first // key
your_map.begin()->second // value
jweyrich
  • 31,198
  • 5
  • 66
  • 97
7

begin() returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first and ->second of that iterator)

Nim
  • 33,299
  • 2
  • 62
  • 101
6

You can use the iterator that is returned by the begin() method of the map template:

std::map<K, V> myMap;
std::pair<K, V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Marcus Gründler
  • 945
  • 13
  • 16
  • 1
    Quite the opposite: It stores its content in an ordered fashion, based on comparisons of the keys! – Oliver Charlesworth Jan 28 '11 at 09:03
  • 1
    Yes folks, you are absolutely right. It is ordered by key order. What I meant to say is, that the order of insertion is not preserved, i.e. the first added entry to the map is not neccessarily the one at **begin()**. – Marcus Gründler Jan 28 '11 at 10:08
0

*my_map.begin(). See e.g. http://cplusplus.com/reference/stl/map/begin/.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680