无法推断出 std::map.insert 的模板参数

5
我正在尝试熟悉STL库,但我无法理解编译错误。我已经搜索了其他使用编译器错误字符串“could not deduce template argument for…”的问题,但没有一个答案是适用或相关的。
以下是错误信息: Error 4 error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional 125
我正在编写一个简单的解释器来计算一元函数的导数/积分。我想要一个映射表将用户输入与内部控制代码匹配。键是三角函数(或其他函数),而int是控制代码。我使用一个单独的头文件来#define函数,但是对于这个例子,我只是使用整数字面量。我正在使用Visual Studio。
#include <cstdio>
#include <map>
using namespace std;
int main(int argc, char** argv) {
    map< string, int > functions;
    functions.insert( pair<string, int>("sin", 1) );

    return 0;
}

编辑:

尝试了Serge的(可行的)答案后:

functions.insert(std::make_pair(std::string("sin"), 1));

我意识到了错误并尝试了这个方法:

pair<string, int> temp = pair<string,int>("cos",2);
functions.insert(temp);

尽管这可能不是最佳选择,但它说明了在将对对象插入映射之前没有构造对对象的问题。

1
使用 std::map<X,Y>::value_type 就是 std::pair<*const* X, Y> - JoeG
1
同时 functions["sin"] = 1; 也可以完美地工作 :-) - Martin Kristiansen
@MartinKristiansen 这就是我会做的。它略微昂贵,并要求值具有默认构造函数。对于整数来说没问题,但对于某些类来说可能是禁止或不可能的。 - Peter Wood
关于您的编辑:您不需要在插入之前定义temp,那不是错误,而且您也不需要调用make_pair - 尽管它有一个不需要显式指定类型的优点 - pair构造函数也可以工作。实际上,我会投票支持@MartinKristiansen的解决方案,因为它既简短又易读。 - Christian Ammer
2个回答

8

请确保您已经包含了string头文件。

#include <map>
#include <utility>
#include <string>

...

std::map<std::string, int> functions;
functions.insert(std::make_pair(std::string("sin"), 1));

只需简单地添加#include <string>就解决了错误。你还可以执行functions["newkey"] = 1; - IssamTP

3
  1. 您没有包含 <string>
  2. char** argv[] 必须是 const char* argv[]

谢谢,但我仍然有这两个错误。 IntelliSense:没有重载函数的实例,以及错误C2664无法转换参数... - xst
嗯,在插入头文件后,我可以编译您的代码而没有错误。 - Christian Ammer
在包含<string>并将char** argv[]更正为const char* argv[]之后,GCC编译您的代码时不会出现错误 - Christian Ammer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接