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

share|improve this question
Is this an XY question? Is your goal to create a vector<Wrap> or to get boost::lambda working? – Pubby Jan 17 at 9:18
create a vector<Wrap>. – balki Jan 17 at 9:33

2 Answers

up vote 1 down vote accepted

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 .

share|improve this answer
Thanks. But I was trying to avoid creating a separate function. Looks like it is not possible. So I will accept this solution – balki Jan 19 at 11:35

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.

share|improve this answer
Thanks. But in my real usecase. I already have a struct populated with some values. I just want to replicate the struct and change one of the member – balki Jan 17 at 10:15
You'll have to write a function to do that, since you can't return a modified struct when you change a member. – yiding Jan 17 at 10:22

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.