我有一個std::shared_ptr鍵和值的's映射,我正在嘗試找到正確的元素。下面是我所擁有的,但它仍然有問題并且無法編譯。
std::map<std::shared_ptr<MyObjA>, std::shared_ptr<ValObj>> aobjs;
std::map<std::shared_ptr<MyObjB>, std::shared_ptr<ValObj>> bobjs;
template <typename T>
int findit(T& t)
{
T myobj = t;
typename std::map<std::shared_ptr<T>, std::shared_ptr<ValObj>>::iterator it;
if constexpr(std::is_same<T, net::MyObjB>::value) {
net::MyObjB objB;
// failing here ...
auto it = std::find_if(bobjs.begin(), bobjs.end(),
[&](std::shared_ptr<MyObjB> const& p) {
return *p == objB;
});
if (it != bobjs.end()) {
// found it
return 0;
}
}
return -1;
}
我認為這個問題是與first和last的的find_if回傳std::shared_ptr,但不確定。我得到了大量無法決議的輸出......
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g -v10/bits/predefined_ops.h: In instantiation of ‘constexpr bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = findit<MyObjB>::<lambda(const std::shared_ptr<MyObjB>&)>]’:
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g -v10/bits/stl_algobase.h:1912:42: required from ‘constexpr _InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<findit<MyObjB>::<lambda(const std::shared_ptr<MyObj>&)> >]’
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g -v10/bits/stl_algobase.h:1974:23: required from ‘constexpr _Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<findit<MyObjB>::<lambda(const std::shared_ptr<ValObj>&)> >]’
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g -v10/bits/stl_algo.h:3934:28: required from ‘constexpr _IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = findit<MyObjB>::<lambda(const std::shared_ptr<MyObjB>&)>]’
想法?
uj5u.com熱心網友回復:
我有一個
std::shared_ptr鍵和值的's映射……想法?
我想到了一些事情:
1. 拿著這樣的地圖可能不是一個好主意——尤其是在鑰匙方面。擁有需要資源分配的“重”鍵是沒有意義的,并且您可能會避免持有許多副本。
很可能MyObjA's 有一些你可以使用的廉價數字識別符號;如果他們沒有 - 考慮添加這樣的欄位,并MyObjA使用這樣的唯一識別符號進行構建。然后,您可以從 ObjAKey 映射到 MyObjB,甚至從 ObjAKey 映射到 MyObjA 和 MyObjB 的映射,而不是從 MyObjA 到 MyObjB 的映射std::pair。
2. 我懷疑即使對于 map values, astd::shared_ptr也可能不是必需的,但是您沒有給我們足夠的背景關系。
3.你真的需要一個有序的地圖嗎?會std::unordered_map不會為你作業?此外,如果地圖中的元素數量不夠大,您可能只需使用 MyObjA、MyObjB 對的向量就足夠了。標準庫映射并不是很快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365030.html
上一篇:如何在C/C 編程中從其他檔案訪問函式內部的區域靜態變數和區域變數?
下一篇:重復定義?[復制]
