Bibliothèque C ++ Unordered_map - fonction emplace_hint ()

La description

La fonction C ++ std::unordered_map::emplace_hint() insère un nouvel élément dans unordered_map en utilisant hint comme position pour l'élément.

Déclaration

Voici la déclaration de la fonction std :: unordered_map :: emplace_hint () de l'en-tête std :: unordered_map.

C ++ 11

template <class... Args>
iterator emplace_hint(const_iterator position, Args&&... args);

Paramètres

  • position - Astuce pour la position d'insertion de l'élément.

  • args - Arguments transmis pour construire le nouvel élément.

Valeur de retour

Renvoie un itérateur vers l'élément nouvellement inséré. Si l'insertion échoue en raison d'un élément déjà existant, elle renvoie l'itérateur à l'élément existant.

Complexité temporelle

Constante ie O (1) dans le cas moyen.

Linéaire c'est-à-dire O (n) dans le pire des cas.

Exemple

L'exemple suivant montre l'utilisation de la fonction std :: unordered_map :: emplace_hint ().

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'b', 2},
            {'c', 3},
            {'d', 4},
            };

   um.emplace_hint(um.end(), 'e', 5);
   um.emplace_hint(um.begin(), 'a', 1);

   cout << "Unordered map contains following elements" << endl;

   for (auto it = um.cbegin(); it != um.cend(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

Compilons et exécutons le programme ci-dessus, cela produira le résultat suivant -

Unordered map contains following elements
a = 1
e = 5
d = 4
b = 2
c = 3