objects and vectors.
Author |
Message |
Justin_
|
Posted: Wed Aug 16, 2006 3:59 am Post subject: objects and vectors. |
|
|
Hmm.. Being the noob that I am, I'd like to make a vector of objects. I've only conceptualized the following, but...
Since the constructor of the object initializes its member variables and it is called when you initialize the vector...
c++: |
vector<obj> my_object("Lovely");
|
The constructor is called which takes one string as an argument. In my case, the argument passed to the constructor dictates the rest of the member variable's initializations. For instance if the string is "Lovely" than all the little variables become lovely too. But what if you wanted to throw in some ugly variables?
In my case the initializations are actually functions so there is a lot of overhead and it just wouldn't be practical to let all the values initialize and then go ahead and change them...
Is there a way to call the constructor of each object in the array seperately? Thanks for your time. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Justin_
|
Posted: Wed Aug 16, 2006 4:49 am Post subject: (No subject) |
|
|
woops, okay so "Lovely" would actually be for the std::vector constructor. Still, how do you construct the objects themselves? |
|
|
|
|
|
Null
|
Posted: Wed Aug 16, 2006 10:04 am Post subject: (No subject) |
|
|
This is a possible solution, but it might not be relavent to your problem.
c++: |
#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>
const int SIZE = 10;
int main() {
int elems[] = { 1, 1, 1, 2, 1, 1, 3, 1, 1, 4 };
// initialize the vector to the contents of the array.
// Remember, iterators are generalizations of pointers.
// (if only I could figure out how they are implmented...hmm)
std::vector<int> numbs(elems, elems + SIZE);
// display contents of std::vector<int>
std::copy(numbs.begin(), numbs.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
|
|
|
|
|
|
|
r.3volved
|
Posted: Wed Aug 16, 2006 11:04 am Post subject: (No subject) |
|
|
I'd imagine what you're trying to do is this?
code: |
std::vector<obj> vecObjects;
obj myNewObject();
vecObjects.push_back(myNewObject);
|
or with pointers:
code: |
std::vector<obj*> vecObjects;
obj myNewObject = new obj();
vecObjects.push_back(myNewObject);
|
|
|
|
|
|
|
Justin_
|
Posted: Wed Aug 16, 2006 12:12 pm Post subject: (No subject) |
|
|
Quote:
std::vector<obj*> vecObjects;
obj myNewObject = new obj();
vecObjects.push_back(myNewObject);
Thanks guys, this one is what I was looking for. Sorry for the noob question. |
|
|
|
|
|
r.3volved
|
Posted: Wed Aug 16, 2006 7:19 pm Post subject: (No subject) |
|
|
no noob questions, just noob lack of research
keep in mind that you're using pointers there so you'll be using the -> operator unless you're dereferencing elements of your vector. |
|
|
|
|
|
|
|