map value_comp() in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of map::value_comp() function in C++ STL.

What is a Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.

What is map::value_comp()?

map::value_comp() is an inbuilt function in C++ STL which is declared in  header file. value_comp() returns a copy of the comparison object, which is used by the map container for the comparisons. By default, this object is less than the operator’s object, which works similar to less than operator.

It is a type of function pointer or a function object which does the comparison of the two values of the same type in a particular set and returns true if the first element is smaller than the second element in the container, else it returns false.

Syntax

Map_name.value_comp(key& k);

Parameter

This function accepts no parameter.

Return value

This function returns a comparison object of the associated set container.

Example

Input

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
set<int>::value_compare cmp = myset.value_comp()

Output

1
2
3

Example

 Live Demo

#include <iostream>
#include <map>
using namespace std;
int main() {
   map<char, int> TP = {
      { 'a', 10 },
      { 'b', 20 },
      { 'c', 30 },
      { 'd', 40 },
      { 'e', 50 },
   };
   auto temp = *TP.rbegin();
   auto i = TP.begin();
   cout <<"Elements in map are : \n";
   do {
      cout<< i->first << " = " << i->second<< endl;
   } while (TP.value_comp()(*i++, temp));
   return 0;
}

Output

Elements in map are :
a = 10
b = 20
c = 30
d = 40
e = 50
raja
Published on 15-Apr-2020 12:31:55
Advertisements