【问题标题】:std::map.insert "could not deduce template argument for..."std::map.insert "不能为...推导出模板参数"
【发布时间】:2012-02-21 19:59:23
【问题描述】:

我正在尝试熟悉 STL 库,但我无法理解我的编译错误。我已经使用编译器错误字符串“无法为...推断模板参数”搜索其他问题,但没有一个答案似乎适用或相关。

错误 4 错误 C2784: 'bool std::operator &,const std::unique_ptr<_ty2> &)' : 无法推断出 'const 的模板参数std::unique_ptr<_ty> &' from 'const std::string' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional 125

我正在编写一个简单的解释器来计算一个变量中的导数/积分。我想要一张地图,用于将用户的输入与内部控制代码相匹配。 key 是 trig(或其他)函数,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);

虽然这可能不是最理想的,但它说明了在插入地图之前没有构造对对象的问题。

【问题讨论】:

  • 使用std::map&lt;X,Y&gt;::value_typestd::pair&lt;*const* X, Y&gt;
  • functions["sin"] = 1; 也可以完美运行 :-)
  • @MartinKristiansen 这就是我要做的。它稍微贵一些,并且要求该值是默认可构造的。这对整数来说很好,但对于某些类来说可能是禁止的或不可能的。
  • 关于你的编辑:你不需要在插入之前定义temp,这不是错误,你也不需要调用make_pair——虽然它的优点是没有需要明确指定类型——pair-constructor 也可以工作。实际上我会投票给@MartinKristiansen 解决方案,因为它简短易读。

标签: c++ stl map


【解决方案1】:
  1. 你还没有收录&lt;string&gt;
  2. char** argv[] 必须是 const char* argv[]

【讨论】:

  • 谢谢,但我仍然有这两个错误。 IntelliSense:没有重载函数的实例,错误 C2664 无法转换参数...
  • 嗯,插入标头后,我可以毫无错误地编译您的代码。
  • 在包含&lt;string&gt; 并将char** argv[] 更正为const char* argv[] 之后,还有GCC compiles your code without errors
【解决方案2】:

确保包含 string 标头。

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

...

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

【讨论】:

  • 只需添加 #include 即可解决该错误。你也可以做 functions["newkey"] = 1;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
相关资源
最近更新 更多