Copy values to and from a member of a structure in C++ -


i have structure shown below, use purpose of sorting vector while keeping track of indices.

struct val_order{         int order;         double value; }; 

(1). use loop copy values shown below. first question if there faster way copy values member of structure (not copying entire structure structure)

int n=x.size(); std::vector<val_order> index(n); for(int i=0;i<x.size();i++){        //<------so using loop copy values.     index[i].value=x[i];      index[i].order=i; } 

(2). second question has copying 1 member of structure array. found post here discusses using memcpy accomplish that. unable make work (code below). error message got class std::vector<val_order, std::allocator<val_order> > has no member named ‘order’. able access values in index.order iterating on it. wonder wrong code.

int *buf=malloc(sizeof(index[0].order)*n); int *output=buf; memcpy(output, index.order, sizeof(index.order)); 

question 1

since initializing n vectors 2 different sources (array x , variable i), difficult avoid loop. (you initialize vectors index.assign if had array of val_order filled values, see this link)

question 2

you want copy n order values int array, , memcpy seems convenient that. unfortunately,

  • each element of vector val_order structure, though copy via memcpy not copy int *order* value double *value* value
  • furthermore, dealing vector, internal structure not simple array (vector allows operations not possible regular array) , cannot copy bunch of vector int array giving address of, say, first vector element memcpy.
  • also, memcpy wouldn't work want anyway, expects address - have give, e.g., &index[0] ... again, not want given points above

so have make loop instead, like

int *buf = (int *)malloc(sizeof(int)*n); int *output = buf; (int i=0 ; i<n ; i++) {    output[i] = index[i].order; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -