如何实现排序的指针向量
How to implement sorted pointer vector?
我想实现一个排序的指针向量,例如以下
#include <vector>
#include <memory>
#include <algorithm>
//! A random accessed vector with sorted allocated elements.
//! - Elements must be allocated on heap.
//! - The vector manages the memories of its elements.
template<class T, class Compare = std::less<T>>
class SortedPtrVector
{
public:
SortedPtrVector() {}
//! Add an element, return its index.
int Add(T* element)
{
auto position = std::lower_bound(m_vector.begin(), m_vector.end(),
element, Compare); // Wrong here due to compare smart pointers
auto newPosition = m_vector.insert(position, element);
return newPosition - m_vector.begin();
}
private:
std::vector<std::unique_ptr<T>> m_vector;
};
如何实现添加功能?非常感谢。
auto position = std::lower_bound(m_vector.begin(), m_vector.end(),
element, Compare);
这显然是错误的。Compare
是一种类型,而不是对象。
您可以将lambda与Compare
对象使用。所以我认为这应该有效:
Compare cmp;
auto comparer = [&](std::unique_ptr<T> const & a, std::unique_ptr<T> const & b)
{
return cmp(*a, *b); //use cmp here!
};
std::unique_ptr<T> uniqElem(element);
auto position = std::lower_bound( m_vector.begin(),
m_vector.end(),
uniqElem, //not element!!
comparer);
请注意,您不能将element
传递给std::lower_bound
,因为element
是T*
类型,当std::lower_bound
期望std::unique_ptr<T>
类型的值,并且从T*
到std::unique_ptr<T>
没有隐含的转换。另外,出于相同的原因,您不能将element
插入向量。将uniqElem
插入向量。
我建议您将该参数作为unique_ptr
而不是T*
,因为这向用户表明当SortedPtrVector
的对象脱离范围时,添加的项目将自动删除:
int Add(T* element); //bad - doesn't say element will be deleted!
int Add(std::unique_ptr<T> element); //good - says element will be deleted!
如果将std::unique_ptr<T>
用作参数类型,请注意以下要点:
v.Add(new T()); //will not work
v.Add(std::unique_ptr<T>(new T()); //will work
std::unique_ptr<T> item(new T());
v.Add(item); //will not work
v.Add(std::move(item)); //will work
这全是因为std::unique_ptr
不是可复制,但它是可移动。
而不是使用std::less
,您可以这样实现自己的ptr_less
:
template< typename T >
class ptr_less
{
typedef bool result_type;
bool operator ()( T const& left, T const& right ) const
{
return *left < *right;
}
};
一般实施也必须检查 null Pointers 。
另一种方法是使用boost::ptr_vector
代替std::vector
。
相关文章:
- std::排序在共享指针的向量上
- 为什么指针在对二维数组进行排序时无法正常工作?
- C++为什么我的指针选择排序中存在分段错误?
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- 危险指针的内存排序
- 使用指针指向对象C++对向量进行排序
- 指向指针排序向量的指针向量的 C++ 向量
- 对元素的向量或指向元素的指针进行排序
- 智能指针的排序向量:神秘崩溃
- 如何在 c++ 上对指针列表进行排序
- 我对C 中共享指针列表进行排序的功能未完成类型
- 查找排序的容器,其中指向元素的指针在添加/删除时不会更改
- 固定大小的容器,其中元素被排序,并可以为C 中的数据提供原始指针
- 通过其char键对对象指针的C 向量进行排序
- 排序时引用绑定到 'value_type' 类型的 null 指针
- 字符串指针的排序向量
- 对字符串的指针数组进行排序
- 排序阵列会使指针链接错误
- 选择排序指针问题
- 优先级队列排序指针指向改变值的对象.c++