【问题标题】:Error in C++ Vector Usage: No matching member function for call to 'push_back'C++ 向量使用中的错误:没有匹配的成员函数用于调用“push_back”
【发布时间】:2019-05-07 13:10:10
【问题描述】:

我基本上是在尝试使用矢量,但是它存在问题。顺便说一句,我要解决的问题是 USACO 2014 年 12 月铜问题 #4。代码在下面。

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int num,min,max;
    cin>>num>>min>>max;

    vector <pair<int,int> > cow;

    for(int a=0;a<num;num++)
    {
        int temp;
        int temp2;
        cin>>temp>>temp2;

        cow.push_back (temp2);

        if(temp=="NS")
            cow[a].second=0;
        else if(temp=="S")
            cow[a].second=1;
    }

    sort(cow.begin(),cow.end());

    int count=0;

    cout<<"Count="<<count<<endl;

    for(int b=0;b<num;b++)
    {
        cout<<"Weight: "<<cow[b].first;
        if(cow[b].second==0)
            cout<<"Spots: NO"<<endl;
        else if(cow[b].second==1)
            cout<<"Spots: YES"<<endl;
    }
}

预期的结果应该是向量应该按数字顺序排列,但我卡在第一步。此外,它给我的错误说:No matching member function for call to 'push_back'

我不知道如何处理这个问题,我也找不到任何关于类似问题的在线资源。有人可以帮忙吗?

*edit: 将 int temp 更改为 string temp

【问题讨论】:

  • cowvector &lt;pair&lt;int,int&gt; &gt; 而不是 vector&lt;int&gt;
  • cow.push_back (temp2);?你的意思是cow.push_back({ temp, temp2 });?此外,那些 if (temp == "NS") 比较不适用于 int 和字符串文字。
  • 我刚刚添加了问题参考,供可能想要查看问题并查看它是否有帮助的人使用。老实说,这不是创建算法的问题,而是创建并将值输入向量的基本问题,所以我认为这并不重要。
  • 在您了解类型之前,原因并不明显,但this(和this)是一个在线资源,可以非常全面地回答您的问题。还有this.

标签: c++ vector


【解决方案1】:

您声明了一个成对向量,但正在将一个 int 推回到向量中

【讨论】:

  • ` 向量 > 牛; for(int a=0;a>温度>>温度2;牛.push_back (temp2,0); if(temp=="NS") 牛[a].second=0;否则 if(temp=="S") 牛[a].second=1; } ` 这是我所做的更改,但它产生了相同的错误。
  • @SeanKim,发送两个单独的整数是行不通的。您需要创建一个pair&lt;int, int&gt; 对象以发送到 push_back。 cow.push_back( {temp2, 0} );
  • @brady 在这种情况下,我将如何输入pair&lt;int,int&gt; 对象的值?
  • @SeanKim 确定push_back 之前的第二个元素,而不是之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2020-08-25
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
相关资源
最近更新 更多