创建局部结构的 std::向量时出错
Errors creating std::vector of local structure
#include <vector>
int main() {
struct st { int a; };
std::vector<st> v;
for (std::vector<st>::size_type i = 0; i < v.size(); i++) {
v.operator[](i).a = i + 1; // v[i].a = i+1;
}
}
上面的代码在使用 GNU g++ 编译器编译时给出了以下错误。
test.cpp: In function ‘int main()’:
test.cpp:6:19: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::st’
test.cpp:6:19: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
test.cpp:6:19: error: template argument 2 is invalid
test.cpp:6:22: error: invalid type in declaration before ‘;’ token
test.cpp:7:24: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::st’
test.cpp:7:24: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
test.cpp:7:24: error: template argument 2 is invalid
test.cpp:7:37: error: expected initializer before ‘i’
test.cpp:7:44: error: ‘i’ was not declared in this scope
test.cpp:7:50: error: request for member ‘size’ in ‘v’, which is of non-class type ‘int’
test.cpp:8:20: error: request for member ‘operator[]’ in ‘v’, which is of non-class type ‘int’
为什么我无法创建结构向量?
在 C++11 之前,您无法使用本地类实例化模板。您有两种选择:
1)将st
定义置于main
之外
#include <vector>
struct st { int a; };
int main()
{
std::vector<st> v;
}
2) 使用 c++11 编译器编译
相关文章:
- 在 c++ 的构造函数中分配对象向量时出错
- 使用复向量时出错
- 我在尝试将多个值push_back向量时出错。我做错了什么?
- parallel_for lambda 函数填充 2D 向量后出错
- 修改另一个类的向量成员时出错
- 使用类作为向量类型时出错 - "Undeclared identifier"
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- Cgal::D ynamic_dimension_tag 在尝试构建点向量时出错
- 当试图将C++矩阵和向量乘法Seg存储到求和中时,它们会出错
- 在成对向量中查找函数时出错
- 创建局部结构的 std::向量时出错
- 尝试在头文件上私下声明向量时出错
- 搜索向量时出错
- 将一个向量(从向量的一个向量中提取)分配给另一个向量时出错,运算符为
- 将int推送到向量时出错
- Visual Studio报告对结构向量的push_back()函数调用出错
- 对向量进行操作后返回时出错
- 在向量中遍历结构成员时出错
- 将随机数与向量大小进行比较时出错
- 从数组初始化向量出错