c++ - 构造一个数组的有效方法,该数组从 C++ 中的另一个数组中获取具有给定索引的元素

标签 c++ arrays vector indices

是否可以从另外两个数组创建一个数组,一个是源数组,第二个包含要获取的元素的索引,在 C++ 中,仅使用一个命令,没有循环,例如,使用 STL 或促进?例如,给定

double X[10] = [10., 9., 8., 7., 6., 5., 4., 3., 2., 1.];

int n[4] =  [0, 1, 3, 9];

我想拥有

double X[4] = [10., 9., 7., 1.]

作为结果。 在 MATLAB 中,我会简单地编写类似 X(n) 的内容。

最佳答案

使用 c++11-features 你可以这样做:

  std::vector<double> vec;
  std::transform(std::begin(n), std::end(n), std::back_inserter(vec), [&](int idx)
  {
    return x[idx];
  });

如果没有 c++11,它可能看起来像这样:

template <typename T, std::size_t N>
struct Get_Idx
{
  Get_Idx(T (&t)[N]) : m_t(t) { }

  T (&m_t)[N];

  T operator()(std::size_t i) const
  {
    return m_t[i];
  }
};

template <typename T, std::size_t N>
Get_Idx<T, N> get_idx(T (&t) [N])
{
  return Get_Idx<T, N>(t);
}

  std::vector<double> vec2;
  std::transform(n, n + 4, std::back_inserter(vec2), get_idx(x));

此外,您为什么使用 c 数组而不是 STL 容器?

关于c++ - 构造一个数组的有效方法,该数组从 C++ 中的另一个数组中获取具有给定索引的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211835/

相关文章:

c++ - 获取调用堆栈的大小

c++ - Clang 格式的换行符

c++ - 将数学表达式传递给函数

python - Numpy Array 获取按行搜索的行索引

c++ - 返回对 vector 元素的引用

c++ - 光线拾取方向计算不正确

javascript - 如何在展开前将事件的 Accordion 滚动到顶部

java - 防止二维数组中的 indexoutofboundsexception

c++ - vector of vector的初始化很慢

c++ - 连接两个 vector 的最佳方法是什么?