confused about vectors and structure

Nov 23, 2011 at 2:35am
Say I have a structure:

1
2
3
4
5
6
7
8
struct A{
    A(int size);
    vector<int> myvec;
};

A::A(int size) {
    myvec.resize(A);
}


So now I have my structure called "A" which I can create using A newinstance(5); or something along those lines. But what happens if I have a vector that contains these structures? Like:

1
2
vector<A> myvec;
myvec.resize(5);


What on earth is inside myvec now? It can't have called the constructor because I didn't give it a "size" value, and the default destructor no longer exists... I realize that I lack some basic understanding of how all this stuff works, but it would be great if someone could shed some light on it.
Last edited on Nov 23, 2011 at 3:51am
Nov 23, 2011 at 3:47am
This didn't even compile for me until I gave the constructor parameter a default value. I also renamed the member vector to make things a little clearer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>
using namespace std;

struct A
{
	A(int size=0) {m_myvec.resize(size);}
private:
	vector<int> m_myvec;
};

int main ()
{
	vector<A> myvec;
	myvec.resize(5);
}


So, I'm not sure what you were trying to do, but with my code, you've got a vector of 5 elements. Each element contains a struct A with an uninitialized vector.
Topic archived. No new replies allowed.