Following program looks pretty OK to me. But I can not get it compiled.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
struct a
{
int i;
int j;
};
std::vector<a*> vecA;
a* pA = new a;
pA->i = 4;
pA->j = 9;
vecA.push_back(pA);
return 0;
}
It generates following error.
struct_update.cc: In function ‘int main()’:
struct_update.cc:32:19: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::a*’
struct_update.cc:32:19: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
struct_update.cc:32:19: error: template argument 2 is invalid
struct_update.cc:32:25: error: invalid type in declaration before ‘;’ token
struct_update.cc:39:10: error: request for member ‘push_back’ in ‘vecA’, which is of non-class type ‘int’
You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.
You can actually create a vector of structs!
To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews . The & operator gets the address of something, and it's this that you want to assign to the pointer. *pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to').
Having vector of objects is much slower than a vector of pointers. The results are because algorithms such as sorting need to move elements inside the container. So they not only read the data but also perform a copy (when the algorithm decides to swap items or move to a correct place according to the order).
This isn't true anymore in the new C++11 standard, but current compilers don't fully implement it yet.
A local type can't be a template parameter. Move your structure definition above main
, and everything will work.
Or update your compiler to one that supports this part of C++11.
Here's the restriction from C++03 section 14.3.1 ([temp.arg.type]
), which is removed in C++11:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
Move the structure definition out of main function.
struct a
{
int i;
int j;
};
int main()
{
std::vector<a*> vecA;
a* pA = new a;
pA->i = 4;
pA->j = 9;
vecA.push_back(pA);
In C++03 you cannot do this
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
In C++11 i think you can according to the standard. Even though my Visual Studio 11 compiler refuses to allow it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With