【发布时间】:2016-12-16 15:39:47
【问题描述】:
我有这个我们前段时间写的函数:
template <class C, class T>
static inline bool findClosestObject( const C& container, const TimeUnit& now, T& object );
-
C是 T 元素的容器 -
TimeUnit是一个封装日期和时间的类 -
T是一个带有TimeUnit信息的对象
此函数在容器中进行二分搜索(使用std::lower_bound)以找到最接近now 的对象。
当我们进行二分搜索时,必须对容器进行排序。此功能在很多地方与多种容器一起使用(C 可以是std::vector、std::set、std::map...)。有时我们使用 sorted std::vector 而不是 std::set,因为它们的内存管理速度更快,并且还用于历史问题以及与使用向量的其他代码的兼容性。
问题是我在代码中找到了一个位置,其中一个名为 findClosestObject 的开发人员使用一个未排序的容器......很好的错误......我无法安全地识别所有可以这样做的地方。
所以我现在需要通过在这种不存在的特定情况下对容器进行排序来防止这种情况发生(会很慢,但至少可以工作并保证函数返回我们希望它返回的内容)
所以我尝试修改我的功能:
template <class C, class T>
static inline const C& fixOrder( const C& container, C& temp )
{
if ( std::is_sorted( container.begin(), container.end() )
{
return container;
}
else
{
assert( false ); // to alert developper
// in Release, fix the issue to have function work!
temp = container;
std::sort( temp.begin(), temp.end() );
return temp;
}
}
template <class C, class T>
static inline bool findClosestObject( const C& originalContainer, const TimeUnit& now, T& object )
{
C temp;
const C& container = fixOrder( originalContainer, temp );
...
// leave old code unchanged
}
但是当C 是std::set 或std::map 时编译失败。因为std::sort 不允许用于那种容器...
fixOrder 可以写成只为std::vector 做事而不为其他容器做事吗?
【问题讨论】:
-
为什么不为
std::vector<T>添加重载?
标签: c++ sorting c++11 vector stl