我會避免這樣做,因爲最後一個人回答。我明白你要去哪裏你的容器要將一些更復雜的操作包裝成更簡單的方法,並且認爲你可以在某些時候更改底層容器而不必更改接口。然而,話雖如此,你的對象應該模擬你的業務需求,然後這些對象的實現將使用任何數據容器和訪問模式是最好的。我想我所說的是,你最終不會重新使用這個新的向量類,因爲每次你的業務需求的數據訪問都會不同,你會再次使用一些標準的通用容器,比如std :: vector,基於迭代器的算法訪問數據。
現在,如果有一些不存在的算法,您可以爲該特定項目編寫基於迭代器的算法,然後保留可能能夠重用的算法代碼。下面顯示了我寫的一組grep算法,它基於一組交集,但沒有按照我想要的完成。我可以再次使用這個算法。
#include <utility>
#include <algorithm>
// this is a set grep meaning any items that are in set one
// will be pulled out if they match anything in set 2 based on operator pred
template<typename _InputIterator1, typename _InputIterator2,
typename _OutputIterator, typename _Compare>
_OutputIterator
setGrep(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _InputIterator2 __last2,
_OutputIterator __result, _Compare __comp)
{
while (__first1 != __last1 && __first2 != __last2)
if (__comp(*__first1, *__first2))
++__first1;
else if (__comp(*__first2, *__first1))
++__first2;
else
{
*__result = *__first1;
++__first1;
++__result;
}
return __result;
}
'std :: vector :: back()'不,這不是首選的方法。首選的方法是將底層容器抽象出來並在迭代器/整個範圍上操作,或者編寫一個超類函數'bool include(std :: vector const&v,T const&elem)''。 –
Xeo
2012-08-13 20:20:35
他們不經常這樣做,因爲大部分時間,只要在適當的容器上使用適當的算法就足夠了。 – Griwes 2012-08-13 20:22:02