Redeclaring an array
Is there anyway in C++ for me to redeclare an array?
I want the array to have (x*y)+1 elements but the thing is being declared in a class file privately and so won't let me declare it like that. So is there anyway to declare the array as 10 and then change it at a later point to (x*y)+1?
In C++ array types have a fixed size. You want to consider using a std::vector instead of a normal array.
Quote:Original post by Iccarus
any header files needed for that? <apvector.h> isn't it?
#include <vector>
note the lack of a file extension
the vector is a template type in namespace std.
std::vector<int> myVector;
std::vector<int> maparray[length];
is that the correct initialisation (sorry I haven't used vectors before)
is that the correct initialisation (sorry I haven't used vectors before)
If you declare it as a local variable:
As a member variable it's just
You can change the size of the vector with the .resize() member function.
std::vector<int> maparray(length);
As a member variable it's just
std::vector<int> maparray;
You can change the size of the vector with the .resize() member function.
Quote:Original post by Iccarus
std::vector<int> maparray[length];
is that the correct initialisation (sorry I haven't used vectors before)
almost...
std::vector<int> maparray(length);
this will contain length ints.
use this if you want to start with them zeroised
std::vector<int> maparray(length,0);
note that the vector is a dynamic array. it will ensure it has enough room for anything you try to do.
eg.
vector<int> vec;// note that even though we dont specify the length, the vector will ensure there is enoughfor( int i = 0 ; i < 10 ; ++i ) vec.push_back(i);// adds the number to the back of the vectorfor( int i = 0 ; i < vec.size() ; ++i ) std::cout << vec << '\n';
Quote:Original post by rip-off
use this if you want to start with them zeroised
std::vector<int> maparray(length,0);
The 0 is unncessary. When you specify an initial size with the constructor, it automatically zeros the vector elements when the vector is of int type.
Quote:Original post by SiCraneQuote:Original post by rip-off
use this if you want to start with them zeroised
std::vector<int> maparray(length,0);
The 0 is unncessary. When you specify an initial size with the constructor, it automatically zeros the vector elements when the vector is of int type.
sweet.
specialised templates i assume.
didnt know that.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement