c++ - What is the uses of using a pointer in this specific scenario? -


in scenario, have struct data declared.

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

according notes, create

vector<data*> list; 

to add items list, have create new data pointer , set attributes manually.

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

i not see merits of using approach. why can't use this?

vector<data> list; 

to add items list, create new data variable, use list.pushback<variable>;

am right both approaches works?

first of has be

 list.push_back(variable) 

instead of

list.pushback<variable> 

the difference in case 1 create pointer variable, means store adress of variable in list. 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 return address of place in memory variable stored. return value of variable use 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 pointers, means value , not adress of it.

if work without pointers instead

vector<data> list;   data variable; list.push_back(variable); 

instead, store copy of variable in list.

so in case directly address variable like

list[0].getage() 

if create getage() function in struct data.

if don't know how so, easy( maybe not best) way add

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

in struct data.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -