Redeclaring an array

Started by
15 comments, last by M2tM 18 years, 2 months ago
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?
Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D
Advertisement
In C++ array types have a fixed size. You want to consider using a std::vector instead of a normal array.
any header files needed for that? <apvector.h> isn't it?
Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D
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)
Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D
If you declare it as a local variable:
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';
Cheers, you guys.

Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D
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 SiCrane
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.


sweet.
specialised templates i assume.
didnt know that.

This topic is closed to new replies.

Advertisement