Creating array/vector array of duplicate instance types

Basically I want to create an instance of a class and make an array with duplicate entries of the previous instance created.

I don't really think looping through the entire lot and assigning a duplicate is the best method, is there a way I can do this via a constructor or other form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Non-working example of what I want to do
class Test {
public:
   int randomDataMember;
   bool anotherDataMember;
};

int main {
   Test test;
   test.randomDataMember = 3;   
   test.anotherDataMember = true;

   vector<Test, test> bunch(10);  //Of type Test, duplicate instance test
   cout << bunch[5].randomDataMember;

   return 0;
}
Last edited on
Actually, if I understood you right, yes. Vectors have a constructor that might be of interest.
http://cplusplus.com/reference/stl/vector/vector/

-Albatross
Not really sure if I did this right, like that documentation:
Test test;
vector<Test> bunch(test);

Says no matching function call.

Documentation has:
vector (const vector<T,Allocator>& x); //Guessing x is instance of type T
Oh, oh I'm very sorry, but this is Abuse. No no, you'll want 12A, that's just next door.


I have no idea why I put in that Monty Python quote, but it's irrelevant. That constructor you used is a copy constructor provided you have another vector. You'll want the second constructor from the top.

Hey, maybe it wasn't so irrelevant. I didn't specify which constructor, the Python member didn't specify which room 12. ;)

-Albatross

Last edited on
Is:
explicit vector ( size_type n, const T& value= T() );

Equal to:
Test test;
vector<Test> bunch(int, test);
Last edited on
Nope. One's a member of vector, the other IS a vector. :P

I get what you're saying though. You can safely substitute int for size_type and T for Test (provided that your vector is of "type <Test>, which it is).

-Albatross
I'm not sure how to make this work. =(

It looks like it should to me.
Any ideas on how to get this to work? =\
You already posted the solution, so what's the problem?

vector<Test> bunch(10, test);
would create a vector with 10 copies of test, for instance.
Oh right, silly me. I put int instead of a constant number.

Thanks.
Last edited on
Topic archived. No new replies allowed.