mardi 5 septembre 2023

Return type of `std::unordered_map::emplace` [duplicate]

I'm using std::unordered_map in my own class. The code is like the following:

#include <iostream>
#include <unordered_map>

template<class T>
class MSet {
public:
    std::unordered_map<T, int> map;
    MSet(): map(std::unordered_map<T, int>()) {};
    void add(T e);
};

template<class T>
void MSet<T>::add(T e) {
    std::pair<std::unordered_map<T, int>::iterator, bool> ret = map.emplace(e, 1);
    if (ret.second) {
        std::cout << "Added" << std::endl;
    }
}

int main(int, char**){
    MSet<int> mset;
    mset.add(1);
}

The compiler reports the following error for the type of ret in MSet::add:

[build] /home/experiment/main.cpp: In member function ‘void MSet<T>::add(T)’:
[build] /home/experiment/main.cpp:14:57: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _T1, class _T2> struct std::pair’
[build]      std::pair<std::unordered_map<T, int>::iterator, bool> ret = map.emplace(e, 1);
[build]                                                          ^
[build] /home/experiment/main.cpp:14:57: note:   expected a type, got ‘std::unordered_map<T, int>::iterator’
[build] /home/experiment/main.cpp:15:13: error: request for member ‘second’ in ‘ret’, which is of non-class type ‘int’
[build]      if (ret.second) {
[build]              ^~~~~~
[build] /home/experiment/main.cpp: In instantiation of ‘void MSet<T>::add(T) [with T = int]’:
[build] /home/experiment/main.cpp:23:15:   required from here
[build] /home/experiment/main.cpp:14:59: error: cannot convert ‘std::pair<std::__detail::_Node_iterator<std::pair<const int, int>, false, false>, bool>’ to ‘int’ in initialization
[build]      std::pair<std::unordered_map<T, int>::iterator, bool> ret = map.emplace(e, 1);
[build]                                                            ^~~

I know I can replace the following code:

std::pair<std::unordered_map<T, int>::iterator, bool> ret = map.emplace(e, 1);

to

auto ret = map.emplace(e, 1);

and the compiler will not report the error if replaced. I just want to figure out the correct way to declare the type so the type of ret will be clear in my code.

Aucun commentaire:

Enregistrer un commentaire