Creating array/vector array of duplicate instance types

Sep 23, 2010 at 12:40am
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 Sep 23, 2010 at 12:40am
Sep 23, 2010 at 12:47am
Actually, if I understood you right, yes. Vectors have a constructor that might be of interest.
http://cplusplus.com/reference/stl/vector/vector/

-Albatross
Sep 23, 2010 at 12:51am
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
Sep 23, 2010 at 12:54am
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 Sep 23, 2010 at 12:58am
Sep 23, 2010 at 12:58am
Is:
explicit vector ( size_type n, const T& value= T() );

Equal to:
Test test;
vector<Test> bunch(int, test);
Last edited on Sep 23, 2010 at 12:58am
Sep 23, 2010 at 1:00am
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
Sep 23, 2010 at 1:12am
I'm not sure how to make this work. =(

It looks like it should to me.
Sep 23, 2010 at 10:02am
Any ideas on how to get this to work? =\
Sep 23, 2010 at 10:10am
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.
Sep 23, 2010 at 10:40am
Oh right, silly me. I put int instead of a constant number.

Thanks.
Last edited on Sep 23, 2010 at 10:41am
Topic archived. No new replies allowed.