Re: adding local variable/struct to container - problem
"silversurfer" <kietzi@web.de> wrote:
Hello,
I am a little unsure whether this method really makes sense. The goal
is to add an element to a vector. This is the struct and method I am
using:
std::vector<Entry> models;
struct Entry{
int index;
FeatureVector* value;
int object;
};
void ModelContainer::addModel(FeatureVector* pFeatVec,int index, int
object) {
Entry tmpEntry;
tmpEntry.index=index;
tmpEntry.object = object;
tmpEntry.value=pFeatVec;
models.push_back(tmpEntry);
}
To come to my question: Is this method valid as such?
Yes, it's valid.
However, it's not the way I'd do it. I'd make a parameterized
constructor for Entry; then your "addModel" function can become
just one line, like so:
struct Entry
{
Entry(FeatureVector* _value, int _index, int _object)
: value(_value), index(_index), object(_object) {}
FeatureVector* value;
int index;
int object;
};
void
ModelContainer::
addModel(FeatureVector* value, int index, int object)
{
models.push_back(Entry(value, index, object));
}
It does work so far, but I am not sure whether this could
be just luck?
Well, your method should always work; but I like my method
above better, because it's terser.
I know that it could make no sense to return local variables,
because they are destroyed when they get out of scope.
Is it the same thing here?
No.
Am I adding an element which is destroyed after the method
No.
or am I copying the values to a new location by adding them
to the vector and everything is fine?
Yes. The std::vector<whatever>::push_back() function
copies stuff into a vector by value. That is, it uses "copy
semantics", putting a separate copy of its argument into the
vector.
If I dealt with variables, I would use the "new" operator,
but this is not possible with structs isn't it?
You could do that too, if you want. In that case, it's best
to store pointers to the objects in a vector, like so:
#include <iostream>
#include <vector>
struct Gargoyle
{
Gargoyle(char a, int b) : actor(a), eger(b) {}
char actor;
int eger;
};
int main()
{
std::vector<Gargoyle*> Fizzbin;
Fizzbin.push_back(new Gargoyle('a', 97));
Fizzbin.push_back(new Gargoyle('b', 98));
Fizzbin.push_back(new Gargoyle('c', 99));
// ... a bunch of code ...
// ... use elements of Fizzbin somehow ...
// ... a bunch more code ...
// Clear Fizzbin:
std::vector<Gargoyle*>::iterator i;
for (i = Fizzbin.begin() ; i != Fizzbin.end() ; )
{
std::cout << (*i)->actor << " " << (*i)->eger << std::endl;
delete (*i); // delete object at location (*i)
i = Fizzbin.erase(i); // delete pointer from vector
}
return 0;
}
I just created 3 new Gargoyle objects dynamically,
stored pointers to them in a vector, used the objects,
freed the memory to avoid leaks, and erased the pointers
to avoid leaving invalid pointers in the vector.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
lonewolfintj at pacbell dot net
(put "[usenet]" in subject to bypass spam filter)
http://home.pacbell.net/earnur/