using namespace std::rel_ops;
template <typename T, typename A = std::allocator<T> >
class my_vector {
public:
typedef A allocator_type;
typedef typename allocator_type::value_type value_type;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer iterator;
typedef typename allocator_type::const_pointer const_iterator;
public:
friend bool operator == (const my_vector& lhs, const my_vector& rhs) {
return (lhs.size() == rhs.size()) && std::equal(lhs.begin(), lhs.end(), rhs.begin());}
friend bool operator < (const my_vector& lhs, const my_vector& rhs) {
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());}
friend void swap (my_vector& x, my_vector& y) {
x.swap(y);}
private:
allocator_type _a;
pointer _b;
pointer _e; // size
pointer _l; // capacity
private:
bool valid () const {
return (!_b && !_e && !_l) || ((_b <= _e) && (_e <= _l));}
my_vector (const my_vector& that, size_type c) :
_a (that._a) {
assert(c >= that.size());
_b = _a.allocate(c);
_e = _b + that.size();
_l = _b + c;
my_uninitialized_copy(_a, that.begin(), that.end(), begin());
assert(valid());}我正在浏览这段代码片段,而且有很多事情我不明白,因为我是C++新手。
bool valid () const“中,这一行"(!_b && !_e && !_l)”想做什么?它否定了指点,我不知道它是做什么的,也不知道它想实现什么。
my_vector (const my_vector& that, size_type c) :“一行中,'that‘的类型是什么?它是对自己类的引用吗?my_vector (const my_vector& that, size_type c) :“中,这一行在做什么,"_a (that._a) :”?“_a”是一个分配器对象吗?因为在这一行下面有"_a.allocate(c),“和”分配“是分配器的一个成员函数。发布于 2013-07-24 02:04:01
!_x..。(其中x可以是b、e或l。)如果指针_x为0、NULL或nullptr,则为true。
它否定从指针到布尔值的强制转换结果的值。因此,如果没有设置任何指针,则(!_b && !_e && !_l)为true。
2)
const my_vector& that.
..。是对my_vector (实际上是当前类)的引用,因此这可能是一个构造函数,它通过c传递附加信息来复制对象。
3)对象
_a.
..。被声明为allocator_type _a;,其中allocator_type是A的类型--它是默认为std::allocator<T>的模板参数。
看一下:
template <typename T, typename A = std::allocator<T>>
...
typedef A allocator_type;
...
allocator_type _a;
...所讨论的表达式(注释)是一个成员不对称列表(只有一个元素)。
my_vector (const my_vector& that, size_type c) : _a (that._a)
{
// ...
}在本例中,它的基本意思是“用that._a值初始化that._a”,因为两者都有相同的类型,因此调用_a的复制构造函数。
这种类型设置的目的是使gneric编程成为可能。
template<class Container>
void insert_sorted (Container & object,
typename Container::const_reference value)
{
typename Container::size_type const N = object.size(),
find_index = find_sorted(object, value);
if (find_index < N)
object.insert(object.begin()+find_index, value);
else object.push_back(value);
} 只有在所使用的容器定义了
const_referencesize_typeinsert()的方法const_referencepush_back()的方法const_referencehttps://stackoverflow.com/questions/17823983
复制相似问题