user3274263 user3274263 - 9 months ago 30
C++ Question

Vector of structure returns only last value

Sorry I can't paste the full code but I will try my best to explain the problem. I have a vector of structure. I am passing the vector to a function which fills the vector with structure and returns the vector. But when I try to access the vector elements, I get only the last element inserted. I think the problem is somewhere that I am storing the address of the structure and hence vector only retains the last value but i am not sure how to correct this.

Here is my structure:

struct NA
{ element1;
element2;
};


Here is how I pass my vector after declaring it:

Vector<NA> del;
func(del);


Here is my function: ( q is a variable having results from a stored procedure

func(Vector<NA> &dels)
{
NA& del(*new NA);
while(q.nextquery())
{
while(q.nextrow())
{
q.bind(del.element1);
q.bind(del.element2);
dels.insert(&del);
}
return dels.entries()
}

Answer Source
NA& del(*new NA);
while(q.nextquery())
     dels.insert(&del);

Obviously, you are creating only one del object, but you insert it many times in the same vector. At the end, all you vector's entries will point to the same object.

What you want is probably to create a new del object for each entry in your vector. therefore, put the creation statement inside the loop.

func(Vector<NA> &dels)
{  
  while(q.nextquery())
   {
     while(q.nextrow())
     {
         NA& del(*new NA); // <-- Here
         q.bind(del.element1);
         q.bind(del.element2);
         dels.insert(&del);
     }
     return dels.entries()
 }