Redeclaring an array

This topic is 4683 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Share on other sites
In C++ array types have a fixed size. You want to consider using a std::vector instead of a normal array.

Share on other sites
any header files needed for that? <apvector.h> isn't it?

Share on other sites
Quote:
 Original post by Iccarusany header files needed for that? 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;

Share on other sites
std::vector<int> maparray[length];

is that the correct initialisation (sorry I haven't used vectors before)

Share on other sites
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.

Share on other sites
Quote:
 Original post by Iccarusstd::vector 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';

Share on other sites
Cheers, you guys.

Share on other sites
Quote:
 Original post by rip-offuse this if you want to start with them zeroisedstd::vector 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.

Share on other sites
Quote:
Original post by SiCrane
Quote:
 Original post by rip-offuse this if you want to start with them zeroisedstd::vector 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.

1. 1
Rutin
34
2. 2
3. 3
4. 4
5. 5

• 12
• 14
• 9
• 9
• 9
• Forum Statistics

• Total Topics
633340
• Total Posts
3011421
• Who's Online (See full list)

There are no registered users currently online

×