错误必须具有类类型
Error must have class type
我在 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
.
相关文章:
- 类没有命名C++代码中的类型错误
- 不完整类型错误(E0409、E0070、E0515)
- 使用具有结构不完整类型错误的模板
- 不命名构造函数和析构函数上的类型错误
- 返回派生类型时出现协变类型错误
- 为什么此构造函数没有给出不完整的类型错误?
- 定义模板化结构的特征时出现不完整的类型错误
- 使用重载构造函数时出现不完整的类型错误
- 为什么我得到表达式必须有类类型错误?
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 枚举成员不是类型错误
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 非默认析构函数会导致不完整的类型错误
- 为什么按引用传入会导致绑定引用类型错误
- Objective-C C++ 包装器 类型错误的不完整定义
- 输入类型错误
- 当构造函数的参数类型错误时引发异常
- 命名空间中的'bad_cast' 'std' 未命名类型错误
- C UNWORKOWN类型错误