[英]How to store references to objects from one vector in another vector in C++?
我有一個向量std::vector<MyClass> myclass_vec(10)
其中包含10個MyClass
初始化對象。 現在,我想遍歷此向量,並將對每個MyClass
對象的引用存儲在另一個向量std::vector<MyClass> myclass_vec_refs
。 之所以要存儲引用,是因為不必復制對象,並且顯然要引用與myclass_vec
相同的對象。
出於某種原因,這並不能解決問題。 我是否必須像這樣聲明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
? 因為該對象不再存在,或者myclass_vec_refs
向量是否已調整為-1,還是僅指向錯誤的內存?
是否可以在myclass_vec_refs
向量中進行emplace_back
引用? 由於這會在原地創建對象,所以我猜想這是行不通的,只能使用push_back
嗎?
您無法建立參考向量。 為什么?
引用必須始終引用一個實際對象,並且矢量設計必須能夠為您動態創建“空”對象(即默認構造函數)。
但是,您可以創建指針向量。
如果以任何方式修改了另一個向量,則指針將變為無效。 如果這是你的問題,使用地圖或設置來代替。
如這里的回答: 奇怪的模板推導
訣竅是使用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; });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.