2014-02-21 2 views
8
#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 ++.Ошибки создания std :: вектор локальной структуры

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’ 

Почему я не могу создать вектор структур?

+3

Это не возможно, до C++ 11. Передайте '-std = C++ 11' вашему компилятору, и он будет работать. –

ответ

16

Перед C++ 11 невозможно создать шаблоны с локальными классами. У вас есть два варианта:

1) Поместите st определение вне main

#include <vector> 

struct st { int a; }; 

int main() 
{ 
    std::vector<st> v; 
} 

2) Компиляция с C++ 11 компилятором

Смежные вопросы