如何在c++中存储来自一个向量的对象引用到另一个向量

How to store references to objects from one vector in another vector in C++?

本文关键字:向量 一个 另一个 对象引用 c++ 存储      更新时间:2023-10-16

我有一个向量std::vector<MyClass> myclass_vec(10),有10个初始化的MyClass对象。现在我想循环遍历这个向量,并在另一个向量std::vector<MyClass> myclass_vec_refs中存储对每个MyClass对象的引用。我想要存储引用的原因是,我不需要复制对象,显然,引用与myclass_vec中相同的对象。

由于某些原因,这不能作为aspect。我必须这样申报std::vector<&MyClass> myclass_vec_refs吗?

当我在看这里问的其他问题时,我读到了关于std::unique_ptr。如果我改变std::vector<std::unique_ptr<MyClass>> myclass_vec(10),那么我将无法在myclass_vec_refs中拥有引用或指针,因为它们被声明为唯一的。如果我说错了,请纠正我。

另一种方法是使用std::shared_ptr。因为它持有一个引用计数器,所以我可以让myclass_vec_refs指向myclass_vec中的对象,但是我读到这引入了相当多的开销,并且share_ptr只能作为最后的手段使用。

我也不知道引用我的尝试是否奏效。如果删除myclass_vec中的对象会发生什么?是myclass_vec_refs矢量调整大小-1,因为对象不存在了,还是它只是指向坏内存?

是否有可能在myclass_vec_refs向量中emplace_back引用?因为这创建了对象在地方,我想这不起作用,只有push_back可以使用?

不能创建引用向量。为什么?

一个引用必须在任何时候都指向一个实际的对象,并且vector的设计必须能够动态地为你创建"空"对象(即默认构造函数)。

你可以创建一个指针向量。

如果以任何方式修改了另一个向量,指针将失效。如果这对您来说是一个问题,请使用mapset

答案如下:奇怪的模板演绎

技巧是使用std::reference_wrapper<>
#include <algorithm>
#include <iostream>
#include <vector>
template<typename container_ty_, class Comp>
auto where(container_ty_& V, Comp&& comp)
{
    using value_type = typename container_ty_::value_type;
    using reference =
    std::conditional_t<
      std::is_const<container_ty_>::value,
        std::reference_wrapper<const value_type>,
        std::reference_wrapper<value_type>
    >;
    std::vector<reference> cursor;
    for(auto& VAL : V)
        if(comp(VAL))
            cursor.push_back(VAL);
    return cursor;
}
int main(int argc, char** argv) {
    std::vector<int> tVect = {0, 5, 2, 1, 7, 9};
    //Why must std::vector<int> be passed...
    auto vec = where(tVect, [](const int& V) -> bool { return V > 5; });
    std::for_each(vec.begin(), vec.end(), [] (int& v) { std::cout << v++ << std::endl; });
    std::cout << std::endl;
    std::for_each(tVect.begin(), tVect.end(), [](const int& v) { std::cout << v << std::endl; });
}