STL中vector的底层解析及简易实现

vector是一种动态增长的数组,当原始容量被用尽后,在别的地方进行扩充,大小为原来的2倍,然后将内容拷贝过去;成长过程如下图所示;

STL中vector的底层解析及简易实现_第1张图片

下面是vector的关键源代码;

template
class vector {
public:
	typedef T value_type;
	//vector中的迭代器就是一个指针
	typedef value_type* iterator;
	typedef value_type& reference;
	typedef size_t size_type;
protected:
	iterator start;
	iterator finish;
	iterator end_of_storage;
public:
	iterator begin() { return start; }
	iterator end() { return finish; }
	size_type size() const
	{
		return size_type(end() - begin());
	}
	size_type capacity() const
	{
		return size_type(end_of_storage - begin());
	}
	bool empty() const { return begin() == end(); }
	reference operator[](size_type n)
	{
		return *(begin() + n);
	}
	reference front() { return *begin(); }
	reference back() { return *(end() - 1); }
}

void push_back(const T& x) {
	//尚有备用空间
	if (finish != end_of_storage) {
		construct(finish, x);
		++finish:
	}
	else //已经没有备用空间了
		insert_aux(end(), x);
}

template 
void vector::insert_aux(iterator position, const T& x) {
	if ();
	else {
		const size_type old_size = size();
		//如果原大小为0,则分配1;
		//如果原大小不为0,则分配原大小的两倍
		//前半段用来放原始数据,后半段准备用来放置新数据
		const size_type len = old_size != 0 ? 2 * old_size : 1;
		iterator new_start = data_allocator::allocate(len);
		iterator new_finish = new_start;
		try {
			//将原vector的内容拷贝到新vector
			new_finish = uninitialized_copy(start, position, new_start);
			//为新元素设定初值
			construct(new_finish, x);
			++new_finish;
		}
		catch (...) {

		}
	}
}

vector重载运算符<<

template 
std::ostream& operator << (std::ostream& out, std::vector vec) {
    for (auto it(vec.begin()); it != vec.end(); it++) {
        out << *it;
        if (vec.end() != it + 1)
            out << ",";
    }
    return out;
}


 

你可能感兴趣的:(C++,STL)