c++ - Merging two vectors into a third by even indices from the first vector and odd indices from the second -
i'm trying merge 2 vectors third 1 copying/merging elements @ indices first, , copying/merging elements @ odd indices second.
note: both vectors 2 dimensional.
i have following logic, doesn't seem work:
void pattern::mergepatters( void ) { cout<<"\n merge patters"<<endl; patter_input.reserve( patter_one.size() + patter_two.size() ); for( int i=0;i<patter_one.size(); i++ ){ for( int j =0; j<patter_one[i].size(); j++){ if(j%2==0){ patter_input.push_back( patter_one[j]); } } //cout<< " patter_one answers["<<i<<"]= " << answers_p1[i]<<endl; } for( int i=0;i<patter_two.size(); i++ ){ for( int j =0; j<patter_two[i].size(); j++){ if(j%2!=0){ patter_input.push_back( patter_two[j]); } } //cout<< " patter_one answers["<<i<<"]= " << answers_p1[i]<<endl; } } void pattern::printmergepatters ( void ){ cout<<"\n printmergepatters "<<endl; ( int i=0;i<patter_input.size();i++){ for( int j =0; j<patter_input[i].size(); j++){ cout << " merge patter["<<i<<"]["<<j<<"]= " << patter_input[i][j]<<endl; } } }
i suggest perform copy in 1 loop, instead of using two. may easier using iterators patter_one
, patter_two
arrays, i'll use indices instead.
const unsigned int total_size = patter_one.size() + patter_two.size(); patter_input.reserve(total_size); unsigned int p1_index = 0u; unsigned int p2_index = 0u; (unsigned int = 0u; < total_size; += 2u) { patter_input.push_back(patter_one[p1_index]); patter_input.push_back(patter_two[p2_index]); ++p1_index; ++p2_index; }
notice increment of loop 2 because there 2 array elements pushed in each iteration.
edit 1: copying odd , elements
copy elements patter_one
, odd elements patter_two
, change index initialization values , index increments:
unsigned int p1_index = 0u; unsigned int p2_index = 1u; (unsigned int = 0u; < total_size; += 2u) { patter_input.push_back(patter_one[p1_index]); patter_input.push_back(patter_two[p2_index]); p1_index += 2; p2_index += 2; }
the requirements need clarification, presented 2 alternatives. amount reserved may not correct depending on sizes of patter_one
, patter_two
vectors. above fragment copies half of patter_one
, patter_two
vectors, original reserve
quantity may not correct.
the reserve amount copying half of patter*
vectors is:
const unsigned int total_size = patter_one.size() / 2 // items + patter_two.size() / 2; // odd here.
Comments
Post a Comment