我将从代码开始:

#include <iostream>
#include <vector>
using namespace std;
struct A
{
    int color;

    A(int p_f) : field(p_f) {}
};
int main ()
{
  A la[4] = {A(3),A(5),A(2),A(1)};
  std::vector<int> lv = {begin(la).color, end(la).color};//I would like to create vector from specific value from array la
  for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) std::cout << ' ' << *it;
  return 0;
}

通常我想从数组中的特定值创建一个 vector 。
如您所见, la 是一个数组,我想创建不包含整个 la 数组而只包含颜色的 vector 。
vector(int) 不是 vector(A),哪个 vector{3,5,2,1},所以不是 A,而是只有 int 颜色。它也可以在 C++11 中使用。谢谢。

最佳答案

这应该有效。

std::vector<int> lv;
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), [](const A& a){
    return a.color;
});

这里还有另一种方式:

重构您的结构以从方法中获取颜色:
struct A
{
    int color;

    A(int p_f) : color(p_f) {}

    int getColor() const {
        return color;
    }
};

在这种情况下,您可以使用 bind :
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::bind(&A::getColor, std::placeholders::_1));

或者你也可以使用 std::mem_fn 到稍微短一点的方法(感谢@Piotr S.):
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::getColor));

或者您可以使用 std::mem_fn 到数据成员。在这种情况下,您甚至不需要实现 getter 方法:
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::color));

关于c++ - 如何从数组中的特定值创建 vector ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30887603/

10-11 22:55
查看更多