开发者

Vector of Type to Array of Type::Member?

I have a type like this:

class Foo {
public:
    int bar[3];
    /*Possibly some other members in here*/
};

What is an effective way to get a std:vector<Foo> to an array of int? The array should be a sequential mapping of bar the the开发者_运维百科 Foos of the vector.

Is this enough?

int* array = new int[foos.size() * 3];
int offset = 0;
BOOST_FOREACH(Foo& f, foos) {
    memcpy(array + offset, f.bar, sizeof(int) * 3);
    offset += sizeof(int) * 3;
}

Or is there a better way?


Why going through the trouble of doing a memcpy call? I'd just iterate over all elements and copy (using the assignment operator) into the new array.


std::vector<int> ivect;
std::transform(foovect.begin(), foovect.end(), std::back_inserter(ivect),
  [](Foo const& f) -> int { return f.bar; });

If you lack lambda support of course you'll have to make a functor to do the same thing. Boost.Bind would be a great place to start on that end.

^^^ Didn't understand the question. Do this:

int * array = new int[foos.size() * 3]; // of course, using this datatype is dumb.
int counter = 0;
std::for_each(foos.begin(), foos.end(), [=array,&counter](Foo const& f)
  {
    for (int i = 0; i < 3; ++i) array[counter++] = f.bar[i];
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜