【问题标题】:How can I fix the missing template arguments before '(' token problem here?如何在此处修复“(”标记问题之前缺少的模板参数?
【发布时间】:2021-10-21 12:55:07
【问题描述】:

我在第 15 行和第 20 行遇到问题,我试图将元素推回对向量中

#include <iostream>
#include <vector>
#include <utility>

using namespace std;


int main()
{
    int x, y, a, b, c, d, j, m, v;
    vector<pair<int, int> > ladder;
    cin >> x >> y;
    for (int i = 0; i < x; i++) {
        cin >> a >> b;
        ladder.push_back(pair(a, b));
    }
    vector<pair<int, int> > snake;
    for (int i = 0; i < y; i++) {
        cin >> c >> d;
        snake.push_back(pair(c, d));
    }
    vector<int> moves;
    cin >> v;
    while (v != 0) {
        moves.push_back(v);
        v = 0;
        cin >> v;
    }
    return 0;
}

我的错误是:

prog.cpp: In function ‘int main()’:
prog.cpp:15:30: error: missing template arguments before ‘(’ token
         ladder.push_back(pair(a, b));
                              ^
prog.cpp:20:29: error: missing template arguments before ‘(’ token
         snake.push_back(pair(c, d));

我这里有代码要测试: https://ideone.com/ZPKP4s

【问题讨论】:

  • 第 15 行是 vector&lt;int&gt; moves;,第 20 行是 cin &gt;&gt; v; - 如果我计算正确 - 最好在相关行后面添加评论,并将确切的错误消息作为文本发布。
  • 另外,您正在使用哪种编译器以及您正在使用哪些命令行选项,尤其是哪种语言标准(CTAD 是 C++17 的新标准)。
  • 使用 C++17 编译器。
  • @RaymondChen 我正在使用 c++14,所以这可能是个问题。但我在评论中使用 scohoe001s 方法解决了这个问题。也许旧版本需要指定,而新版本不需要
  • C++14 要求您指定类型。 C++17 添加了一个名为 CTAD 的功能,可以让您省略它。 C++14 确实有一个简化的对构造机制:ladder.push_back(std::make_pair(a, b))。或者您可以使用ladder.emplace_back(a, b) 并让emplace 进行配对。

标签: c++ data-structures std-pair


【解决方案1】:

std::pair 的模板参数deduction 直到 C++17 才起作用。

您需要显式指定模板参数std::pair&lt;int,int&gt;(a, b),或者完全绕过它并使用vector emplace_back 成员函数就地构造pair,它将给定的参数转发给@ vector 原样中的 987654329@ 构造函数:

ladder.emplace_back(a, b);
// ...
snake.emplace_back(c, d);

这里是your code,改用emplace_back

【讨论】:

    【解决方案2】:

    您的问题在于这两行:

    ladder.push_back(pair(a, b));
    ladder.push_back(pair(c, d));
    

    您需要指定这些是什么类型的对:

    ladder.push_back(pair<int, int>(a, b));
    ladder.push_back(pair<int, int>(c, d));
    

    【讨论】:

    【解决方案3】:
    ladder.push_back(pair(a, b));
    

    你应该传递 std::pair 类的模板参数

    ladder.push_back(pair<int, int>(a, b));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 2015-09-12
      • 2017-10-13
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多