#include <iostream>
#include <map>
#include <utility>
int main()
{
std::pair<std::string, std::string> p;
std::map< std::pair<std::string, std::string>, short> m;
// p = std::make_pair("A", "a1");
m.insert(std::make_pair("A", "a1"), 10);
return 0;
}
This code is throwing the following error
maptest.cpp: In function ‘int main()’:
maptest.cpp:9: error: no matching function for call to
‘std::map<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int,
std::less<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >, std::allocator<std::pair<const
std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int> > >::insert(std::pair<const char*,
const char*>, int)’
I am trying to do a std map insertion. The kwy is a std pair and value is a short. But I am getting the above mentioned error. What am I doing wrong here? Pleas help.
The insert function takes a pair. You need
m.insert(std::make_pair(std::make_pair("A", "a1"), 10));
Alternatively, you could use the emplace function:
m.emplace(std::make_pair("A", "a1"), 10);
As a side note, in programmers' vernacular, the word "throw" has a specific meaning relating to exceptions. In your case you are just getting a compilation error.
There is simply no insert method with key and value arguments ie map<...>::insert(K key, V value)
. Instead it accepts key-value pair, so this code should work:
#include <iostream>
#include <map>
#include <utility>
int main()
{
std::pair<std::string, std::string> p;
std::map< std::pair<std::string, std::string>, short> m;
auto&& key = std::make_pair("A", "a1");
short value = 10;
auto&& key_value_pair = std::make_pair(key, value);
//Structured bindings are c++17
auto&&[IT, wasInserted] = m.insert(key_value_pair);
return 0;
}
I would recommend using C++17 method try_emplace
which has key and value arguments:
auto&&[IT, wasInserted] = m.try_emplace(key, value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.