我会避免这样做,因为最后一个人回答。我明白你要去哪里你的容器要将一些更复杂的操作包装成更简单的方法,并且认为你可以在某些时候更改底层容器而不必更改接口。然而,话虽如此,你的对象应该模拟你的业务需求,然后这些对象的实现将使用任何数据容器和访问模式是最好的。我想我所说的是,你最终不会重新使用这个新的向量类,因为每次你的业务需求的数据访问都会不同,你会再次使用一些标准的通用容器,比如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