我可以在矢量上创建视图吗?

Gun*_*ein 7 c++ vector c++11

我有一个功能,需要对给定的元素进行排序。原始矢量一定不能更改,因此我需要该矢量的浅表副本。由于我不需要复制元素本身,因为它们只能被读取,所以我决定制作一个指针向量。目前,我有一个简单的循环来填充矢量,但是我想知道是否存在内置/标准解决方案,甚至可能更快。

void calcFindMinLeftAndSort(std::vector<Location>& locationsComplete, std::vector<Location*>& locationsSorted) {
    // ...

    // copy data in new array, to keep the original untouched
    locationsSorted.reserve(locationsComplete.size());
    // looking for locationsSorted.assign(&elements)
    // yes, I could use for each instead
    for (size_t i = 0; i < locationsComplete.size(); i++)
        locationsSorted.emplace_back(&locationsComplete[i]);

    // sort 
    std::sort(locationsSorted.begin(), locationsSorted.end(), compare);
}
Run Code Online (Sandbox Code Playgroud)

附加信息:locationsComplete向量按特定顺序排序,不得更改。该矢量在应用程序运行期间不会改变。排序后的locationSorted向量被另一个函数使用了一次(可以在同一函数中使用,但这种方式看起来更清晰)。返回下一个函数的结果后,locationsSorted向量将退役。因此,它可以看作是寿命很短的临时载体。

ein*_*ica 6

您可以做的,并且可能想做的,根本不使用指针 - 只需将索引集排序到locationsCompare,使用比较函数在原始区域中查找值。使用 C++11 轻松搞定:

template <typename T>
std::vector<size_t> get_sorted_positions(const std::vector<T> &v)
{
  std::vector<size_t> indices(v.size());

  std::iota(indices.begin(), indices.end(), 0); // indices now holds 0 ... v.size()-1
  std::sort(indices.begin(), indices.end(),
       [&v](size_t i_1, size_t i_2) { return v[i_1] < v[i_2]; }
  );

  return indices;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 唯一发生变异的数据是索引
  • 不用担心返回长向量;由于称为NRVO 的优化,编译器将使用移动构造函数。
  • 这段代码主要是从这个答案中摘取的,但该方法基本上是民间传说。
  • 您可能还想抽象出您的输入是向量的事实,并仅获取对任意容器的引用(并返回std::vector<typename Container::size_type>);或采用一对迭代器;或在 C++20 中 - 取任意范围。但索引仍然是一个向量。

  • @GunnarBernstein:原始向量没有被改变,einpoklum只是进行查找。(通过 const 引用,这有助于防止修改) (2认同)