简体   繁体   English

使用 boost lambda 设置结构的成员

[英]Setting a member of struct using boost lambda

I am trying to create vector<Wrap> with same values as in v .我正在尝试使用与v相同的值创建vector<Wrap> 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注意:还不能使用 C++11

Update Any clean solution which works in C++03 is fine.更新任何适用于 C++03 的干净解决方案都很好。 Need not use boost lambda不需要使用 boost lambda

You should define a constructor for Wrap :您应该为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. constructor来自boost/lambda/construct.hpp ,它将构造函数包装为函数对象。

Use std::transform() and specify a binary operation function.使用std::transform()并指定一个二元运算函数。 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 .请参阅http://ideone.com/DHAXWs 上的演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM