如何从数组中的特定值创建向量?

use*_*552 4 c++ arrays constructor vector c++11

我将从代码开始:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Vic*_*voy 10

这应该工作.

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

另外还有另外一种方法:

重构您的结构以从方法中获取颜色:

struct A
{
    int color;

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

    int getColor() const {
        return color;
    }
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以使用bind:

std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::bind(&A::getColor, std::placeholders::_1));
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用std::mem_fn更短的方法(感谢@Piotr S.):

std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::getColor));
Run Code Online (Sandbox Code Playgroud)

或者您可以使用std::mem_fn数据成员.在这种情况下,您甚至不需要实现getter方法:

std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::color));
Run Code Online (Sandbox Code Playgroud)

  • `std :: mem_fn(&A :: getColor)`代替`bind`也可以做到这一点,它也适用于数据成员 (3认同)