c++ - How to transfer collection of small vector in a unique vector without copy -


i have map<t,vector<double> >, t=char values vector<double> of length<n n=5. transfer each vector<double> map big vector<double> have length n*mapsize, each vector inserted @ index 5*k. if possible without copying.

#include <vector> #include <map> using namespace std; int main() {     typedef vector<double> vec;     typedef map<char, vector<double> >::iterator itmap;      //create map<char,vector<double>> 2 keys holding resp 2-3 elem vectors     double v_value[] = {1.1,2.4};     vec v(v_value, v_value + sizeof(v_value)/sizeof(double));     map<char,vector<double> > mymap;     mymap['a'] = v;     v.push_back(10);     mymap['b'] = v;      //create vector should small vectors     vec receipt;     receipt.reserve(10);      for(itmap = mymap.begin(); != mymap.end(); ++it) {         it->second.resize(5);         receipt.insert(receipt.end(),it->second.begin(),it->second.end());     } } 

edit: edited solution, copy though.

as explained in comment, it's not possible without copying; each of vectors in map separately managed dynamic array , new vector new big array. values have copied. wouldn't worry this, unless have profiled , seen significant issue.

in spirit, std::copy rescue... de de, de de, dum de dum...

#include <vector> #include <map> #include <algorithm>  template<typename t, size_t n> size_t length(t (&)[n]) {    return n; }  int main() {     typedef std::vector<double> vec;     typedef std::map<char, vector<double> >::iterator itmap;      //create map<char,vector<double>> 2 keys holding resp 2-3 elem vectors     double v_value[] = {1.1,2.4};     vec v(v_value, v_value + length(v_value));     std::map<char,vector<double> > mymap;     mymap['a'] = v;     v.push_back(10);     mymap['b'] = v;      //create vector should small vectors     vec receipt(10);      for(itmap = mymap.begin(); != mymap.end(); ++it) {         std::copy(it->second.begin(), it->second.end(), std::back_inserter(receipt));     } } 

for user defined and/or more complex types double, may more efficient use std::move if target compilers support c++11.

i have demo'd small trick calculating length of array... confused sizeof.

ps hate using namespace std.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -