错误必须具有类类型

Error must have class type

本文关键字:类型 错误      更新时间:2023-10-16

我在 c++ 有点新,当试图编译这段代码时,我得到和错误,我不知道如何修复:

int main()
{
    typedef pair<int,int> nodo;
    int x;
    cin >> x; 
    int *g;                
    g = new int[x];   
    vector <nodo> g;

    g[1].push_back(nodo(2,5));
    g[1].push_back(nodo(3,10));
    g[3].push_back(nodo(2,12));
    g[2].push_back(nodo(4,1));
    g[4].push_back(nodo(3,2));
    for (int i = 1; i <=4; ++i){
        //    cout << i << " -> ";
        for (int j = 0; j<g[i].size(); ++j){
            //    cout << g[i][j].first << " c: " << g[i][j].second << " ";    
        }
        //   cout << endl;
    }
    dijkstra(1, x);
    system("pause");
    return 0;
}

我收到的错误是:

Error: Expression must have a class type.

此处:

int *g;
g = new int[x];
vector <nodo> g; // ERROR: Redeclaration!

您首先将g声明为int*类型,然后将其重新声明为vector<nodo>类型。这是非法的。

此外,如果您希望省略标准名称空间中的类型的std::限定条件,则需要有using namespace std指令。但我不建议你使用它。最好显式地指定std::,或者使用特定的using声明。

例如:

    typedef std::pair<int,int> nodo;
//          ^^^^^
    int x;
    std::cin >> x;
//  ^^^^^
    int *g;
    g = new int[x];
    std::vector <nodo> g;
//  ^^^^^

还要确保你导入了所有必要的标准头文件:

    Type     |  Header
--------------------------
std::vector -> <vector>
std::pair   -> <utility>
std::cin    -> <iostream>

你正在重新声明g,首先它是int*,然后你把它变成vector<int>。我不确定这是如何通过编译器的。

另外,与其使用nodo(1,2),不如考虑使用make_pair。使用new也被认为是不好的做法,您应该使用动态容器,如std::vector或静态容器,如std::array

有两个东西命名为g:

int* g;

vector <nodo> g;

这甚至无法编译。

看起来你想要一个向量数组,在这种情况下你需要像

这样的东西
std::vector<std::vector<nodo> > g(x); // size x vector of vectors.

然后你可以这样做:

g[1].push_back(nodo(2,5));
g[1].push_back(nodo(3,10));

pair不是一个类,因为您没有包含<utility>

您还没有包含<vector><iostream>

这个版本可以编译,我想这就是你想要做的:

// Need to include these headers
#include <utility>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    typedef pair<int,int> nodo;
    int x;
    cin >> x; 
    //int *h;                
    //h = new int[x];   
    //specify size of vector
    std::vector< std::vector<nodo> > g(x);
    g[0].push_back(nodo(2,5));
    g[1].push_back(nodo(3,10));
    g[2].push_back(nodo(2,12));
    g[3].push_back(nodo(4,1));
    g[4].push_back(nodo(3,2));

    for (int i = 0; i < g.size(); ++i){
        std::cout << i << " -> ";
        for (int j = 0; j<g[i].size(); ++j){
                cout << g[i][j].first << " c: " << g[i][j].second << " ";    
        }
         cout << endl;
    }
    //dijkstra(1, x);
    //system("pause");
    return 0;
}

很多问题,你使用g两次为一个。我不确定你想用vector做什么,但也许你想要vector s的vector,它更像这样:

 std::vector< std::vector<nodo> > g(x) ;

那么这个就更有意义了:

 g[0].push_back(nodo(2,5)) ;

vector的第一个元素应该在0而不是1 .