如何在c++中存储来自一个向量的对象引用到另一个向量
How to store references to objects from one vector in another vector in C++?
我有一个向量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的设计必须能够动态地为你创建"空"对象(即默认构造函数)。
你可以创建一个指针向量。
如果以任何方式修改了另一个向量,指针将失效。如果这对您来说是一个问题,请使用map或set。
答案如下:奇怪的模板演绎
技巧是使用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; });
}
- 函数向量_指针有不同的原型,我可以构建一个吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 获取向量C++中第一个值和最后一个值的和
- 从多个源构造一个对象,包括一个对象向量
- 为什么一个向量上的多线程操作很慢
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 将一个向量插入另一个向量的某个位置
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 将指向给定子类的指针从一个向量复制到另一个向量
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 紧凑向量一个小的内存足迹向量