PDA

View Full Version : C++ vector help



abraxas334
April 27th, 2009, 10:02 AM
Hi,
this is probably a very silly question coming from an unexperience programmer.
so i have a class and within that class i have defined a vector like this:


vector<int>Array;

now i want to init the vector in the constructor so it has a certain size and the entries are set to a certain value.

if i was doing this in main or any function if i define a vector i can do it like this:


vector<int>Array(10,0) // has 10 entries with value zero

Is there a syntax like that for initing a vector if it has already been definied as a private variable in a class. Or is this the the only way of giving the vector a size of 10 with values 0 in the constructor of the class


for(int i =0; i<10; i++)
{
Array.push_back(0);
}

i mean this method works fine I was just wondering if there was an alternative.
Thanks a lot

Zugzwang
April 27th, 2009, 10:46 AM
You can do so using assignment. Example:



#include <vector>
using namespace std;

int main() {
vector<int> Array;
Array = vector<int>(10,0);
}

cabalas
April 27th, 2009, 10:47 AM
You can run the constructors of member variables when the class constructor is run, you do this by calling the constructor immediately after the function declaration. I'm not sure if that's the best way to explain but hopefully this example should clarify it.

Test.hh:


class Test {
public:
Test();
Test(int);

private:
std::vector<int> my_vec;
std::vector<int> my_vec2;
}


Test.cc:


#include "Test.hh"

Test::Test() : my_vec(10, 0)
{
// Do Stuff
}


The ':' is needed so that the compiler knows that you are calling the classes member variables constructors. If you have multiple members that you wish to run the constructors of just separate each with a comma like so:



Test::Test() : my_vec(10, 0), my_vec2(20, 1)
{
// Do Stuff
}


You can also use the parameters of the constructor as well like in the following:



Test::Test(int init_value) : m_vec(10, init_value)
{
// Do some stuff
}


Hopefully that clears it up a bit for you.

abraxas334
April 27th, 2009, 11:13 AM
Thanks alot! Makes more sense now!