Question

I am trying to create vector<Wrap> with same values as in v. I tried the below combinations, didn't work!

using namespace std;

struct Wrap
{
  int data;
  //Other members
};

int main()
{
  int a[10] = {2345,6345,3,243,24,234};
  vector<int> v(&a[0],&a[10]);
  Wrap w;
  //Populate other members of w
  vector<Wrap> vw;
  using namespace boost::lambda;
  //transform(v.begin(),v.end(), back_inserter(vw), (bind(&Wrap::data,&w,_1), boost::lambda::constant(w)));
  //transform(v.begin(),v.end(), back_inserter(vw), bind(&Wrap::data,&w,_1), boost::lambda::constant(w));
  //transform(v.begin(),v.end(), back_inserter(vw), ((w.data = _1), boost::lambda::constant(w)));
  //transform(v.begin(),v.end(), back_inserter(vw), ((w.data = _1), w));
  cout << vw.size() << endl;
  BOOST_FOREACH(Wrap w, vw)
  {
    cout << w.data << endl;
  }
}

Note: Can't use C++11 yet

Update Any clean solution which works in C++03 is fine. Need not use boost lambda

Was it helpful?

Solution

Use std::transform() and specify a binary operation function. For example:

#include <iostream>
#include <vector>
#include <algorithm>

struct Wrap
{
    int data;
};

Wrap set_data(int a_new_data, Wrap a_wrap)
{
    a_wrap.data = a_new_data;
    return a_wrap;
}

int main()
{
    int a[10] = { 2345, 6345, 3, 243, 24, 234 };
    const size_t A_SIZE = sizeof(a) / sizeof(a[0]);
    std::vector<Wrap> vw(A_SIZE);

    std::transform(a, a + A_SIZE, vw.begin(), vw.begin(), set_data);

    std::cout << vw[0].data << ','
              << vw[1].data << ','
              << vw[5].data << ','
              << vw[9].data << '\n';
    return 0;
}

See demo at http://ideone.com/DHAXWs .

OTHER TIPS

You should define a constructor for Wrap:

struct Wrap
{
  Wrap(int data): data(data) {}
  int data;
};

And then you can simply do this:

transform(v.begin(),v.end(), back_inserter(vw), constructor<Wrap>());

constructor comes from boost/lambda/construct.hpp, and it wraps a constructor as a function object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top