c++ - Keeping two sorted vectors linked by pointers -


(yes homework)

i trying create simple database person identified name + address combination or unique account number. need able add/delete/access information person when provided acc number or name + addr.

i have created version works without account (using overloaded operator < searching in database lower_bound), trying add account feature.

here i've got:

struct sperson {     string s_name, s_addr;     int s_income, s_expense;     saccount * s_accountptr;      sperson ( const string &, const string & );  // constructor };  struct saccount {     string s_account;     sperson * s_personptr;      sperson ( const string & );   // constructor }; 

the idea have vector of accounts , vector of people , keeping them linked pointers. seemed simple until came across these questions:

  • if create object , insert vector, copy of object created , inserted? or original object?
  • what happens addresses of objects in vector when insert it?
  • can make work somehow?

    bool cdatabase::birth ( const string & name, const string & addr, const string & account ) {      sperson persontoadd = sperson ( name, addr );     saccount accounttoadd = saccount ( account );      spiter = lower_bound ( speople.begin ( ), speople.end ( ), persontoadd );     saiter = lower_bound ( saccounts.begin ( ), saccounts.end ( ), accounttoadd );      if ( ( spiter -> s_name == name &&        spiter -> s_addr == addr ) ||        saiter -> s_account == account ) return false;      persontoadd.s_accountptr = & accounttoadd;   // proabably wrong     accouttoadd.s_personptr = & persontoadd;      speople.insert ( spiter, persontoadd );   // mess pointers?     saccounts.insert ( saiter, accounttoadd );      return true; 

    }

// sorry code formatting killing me, gonna fix asap

if create object , insert vector, copy of object created , inserted? or original object?

if use push_back or insert copy made. if don't want copy use emplace_back. inserting elements anywhere other end of vector inefficient since move elements after insertion point or worse elements.

what happens addresses of objects in vector when insert it?

they might or might not change depending on size of vector , insert. having raw pointers vector elements bad idea. insert in middle or vector grows beyond capacity pointers might point nonsense.

can make work somehow?

yes, use handles instead of raw pointers. , if allowed use different data structures std::map std::unordered_set retrieve accounts/persons instead of having go through vector , compare handles.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -