【问题标题】:Receiving error while calling push_back() method on Vector class object在 Vector 类对象上调用 push_back() 方法时收到错误
【发布时间】:2020-09-27 13:43:47
【问题描述】:

在 Vector 类对象上调用 push_back() 方法时收到以下错误:

error: request for member 'push_back' in 'edges.std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(((std::vector<int>::size_type)a))', which is of non-class type 'int'

我正在尝试使用邻接列表创建图表,但它不起作用

#include <bits/stdc++.h>

using namespace std;

/****************************************/
/// INPUT / OUTPUT
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
/****************************************/
/// GLOBAL DECLARATIONS
int n, m;
const int nmax = 100005;
vector <int> edges;
/****************************************/

inline void readInput()
{
    f >> n >> m;
    for(int  i = 1 ; i <= m ; ++ i)
    {
        int a, b;
        f >> a >> b;
        edges[a].push_back(b);
    }
}

int main()
{
    readInput();
    return 0;
}

抱歉写的不好这是我的第一个问题!

【问题讨论】:

  • 请删除所有与您的问题无关的代码并创建一个正确的minimal reproducible example。然后解释你想要达到的目标以及你希望edges[a].push_back(b); 做什么。

标签: c++ arrays compiler-errors


【解决方案1】:
 edges[a].push_back(b);

edges[a] 从向量中获取第 a.th 个元素。当您使用vector&lt;int&gt; 时,您获得的值为int。而且你不能在 int 上调用 push_back,因为类型 int 没有成员函数 push_back

push_back 顾名思义,将一个新值压入向量的末尾。所以你必须使用edges.push_back(b)

如果您打算在给定位置插入新值,则必须使用std::vector::insert

【讨论】:

    【解决方案2】:

    尝试将edges[a].push_back(b) 更改为edges.push_back(b)

    正如 bolov 评论的那样,请解释一下你想用edges[a].push_back(b) 实现什么。你应该直接在 Vector 类对象上调用 push_back() 方法。

    查看此答案,它可能会对您有所帮助: https://stackoverflow.com/a/34608598/9339019

    【讨论】:

      【解决方案3】:

      通过这样做,您在int 上而不是std::vector 上执行push_back 方法。试试吧:

      edges.push_back(b);
      

      【讨论】:

        猜你喜欢
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2020-06-05
        • 1970-01-01
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多