-1

In this scenario, I have a struct Data declared.

struct Data {
       string first;
       string middle;
       string last;
       int age;
       };

According to my notes, we then create a

vector<Data*> list;

To add items to this list, we have to create a new data pointer and set attributes manually.

Data* variable;
variable=new Data;
list.pushback<variable>

I do not see the merits of using this approach. Why can't we just use this?

vector<Data> list;

To add items to this list, I create a new Data variable, then use list.pushback<variable>;

Am I right to say both approaches works?

Yellow Skies
  • 145
  • 9
  • 1
    It makes you think hard about memory management, exception safety, and how not to do things. – juanchopanza Mar 12 '14 at 10:08
  • possible duplicate of [C++ STL: should I store entire objects, or pointers to objects?](http://stackoverflow.com/questions/141337/c-stl-should-i-store-entire-objects-or-pointers-to-objects) – jfly Mar 12 '14 at 10:12

2 Answers2

1

It is faster. For your case, if you were to do

Data variable;
// change properties here
list.push_back(variable);

you would first create a struct Data on the first line, and then you would copy the entire struct when it was pushed back into the list. Since the struct is larger than a pointer to it, doing so is simply not as computationally efficient as just pushing the struct pointer.

riklund
  • 1,031
  • 2
  • 8
  • 16
1

First of all it has to be

 list.push_back(variable)

instead of

list.pushback<variable>

The difference is that in case 1 you create a pointer to the variable, which means you only store the adress of variable in the list. This code

#include <string>
#include <vector>
#include <iostream>

using namespace std;
struct Data {
    string first;
    string middle;
    string last;
    int age;
};

int main()
{
vector<Data*> list;


Data* variable;
variable = new Data;
list.push_back(variable);

cout << list[0];
cin.get();

return 0;
}

would only return you the address of the place in memory where variable was stored. So to return some value of variable you could use something like

vector<Data*> list;
Data* variable;
variable = new Data;
variable->setage(5);
list.push_back(variable);

cout <<  (*list[0]).getage();
cin.get();
return 0;
}

Where *list[0] dereferences the pointers, that means you get the value and not the adress of it.

If you work without pointers instead

vector<Data> list;


Data variable;
list.push_back(variable);

instead, you would store a copy of variable in the list.

So in this case you could directly address variable by something like

list[0].getage()

if you create a getage() function in the struct Data.

If you don't know how to do so, an easy( maybe not the best) way is to add

public:
    int getage(){
        return age;
    }
    void setage(int x){
        age = x;
    }
};

in your struct Data.

jimbo999
  • 80
  • 7