[英]insert in std::map is throwing error. The key is a std::pair and the value is a short
#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;
}
此代码引发以下错误
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)’
我正在尝试插入标准图。 kwy是一个std对,值是一个short。 但是我遇到了上述错误。 我在这里做错了什么? 请帮助。
插入函数需要一对。 你需要
m.insert(std::make_pair(std::make_pair("A", "a1"), 10));
另外,您可以使用emplace函数:
m.emplace(std::make_pair("A", "a1"), 10);
附带说明一下,在程序员看来,“ throw”一词具有与异常有关的特定含义。 就您而言,您只是遇到编译错误。
根本就没有带有key和value参数的insert方法,即map<...>::insert(K key, V value)
。 相反,它接受键值对,因此此代码应正常工作:
#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;
}
我建议使用具有键和值参数的C ++ 17方法try_emplace
:
auto&&[IT, wasInserted] = m.try_emplace(key, value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.