Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first value from map in C++

Tags:

c++

map

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.

like image 857
adir Avatar asked Jan 28 '11 08:01

adir


People also ask

How do I get the first element of a map?

To get the first element of a Map , use destructuring assignment, e.g. const [firstKey] = map. keys() and const [firstValue] = map. values() . The keys() and values() methods return an iterator object that contains the Map's keys and values.

How do you get the first element of an unordered map?

The unordered_map::begin() is a built-in function in C++ STL which returns an iterator pointing to the first element in the unordered_map container or in any of its bucket.

How do you find the value of a map?

Search by value in a Map in C++ Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”. Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.


2 Answers

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.

like image 140
Benoit Avatar answered Oct 13 '22 04:10

Benoit


As simple as:

your_map.begin()->first // key your_map.begin()->second // value 
like image 33
jweyrich Avatar answered Oct 13 '22 06:10

jweyrich