C++ vector 类学习笔记

来源:互联网 发布:2015年火灾数据统计 编辑:程序博客网 时间:2024/05/23 16:06

作者: tyc611, 2007-01-15 
发表于: http://blog.chinaunix.net/u/18517/showart_232126.html

vector容器类型
   vector容器是一个模板类,可以存放任何类型的对象(但必须是同一类对象)。vector对象可以在运行时高效地添加元素,并且vector中元素是连续存储的。
vector的构造
 
函数原型:
template<typename T>
   explicit vector();                                 // 默认构造函数,vector对象为空
   explicit vector(size_type n, const T& v = T());    // 创建有n个元素的vector对象
   vector(const vector& x);
   vector(const_iterator first, const_iterator last);

注:vector容器内存放的所有对象都是经过初始化的。如果没有指定存储对象的初始值,那么对于内置类型将用0初始化,对于类类型将调用其默认构造函数进行初始化(如果有其它构造函数而没有默认构造函数,那么此时必须提供元素初始值才能放入容器中)。
 
举例:
vector<string> v1;         // 创建空容器,其对象类型为string类
vector<string> v2(10);     // 创建有10个具有初始值(即空串)的string类对象的容器
vector<string> v3(5, "hello"); // 创建有5个值为“hello”的string类对象的容器
vector<string> v4(v3.begin(), v3.end());  // v4是与v3相同的容器(完全复制)
 
vector的操作(下面的函数都是成员函数)
 
bool empty() const;                    // 如果为容器为空,返回true;否则返回false
size_type max_size() const;            // 返回容器能容纳的最大元素个数
size_type size() const;                // 返回容器中元素个数  
size_type capacity() const;            // 容器能够存储的元素个数,有:capacity() >= size()  
void reserve(size_type n);             // 确保capacity() >= n
void resize(size_type n, T x = T());   // 确保返回后,有:size() == n;如果之前size()<n,那么用元素x的值补全。
 
reference front();                     // 返回容器中第一个元素的引用(容器必须非空)
const_reference front() const;                   
reference back();                      // 返回容器中最后一个元素的引用(容器必须非空)
const_reference back() const;
 
reference operator[](size_type pos);   // 返回下标为pos的元素的引用(下标从0开始;如果下标不正确,则属于未定义行为。
const_reference operator[](size_type pos) const; 
reference at(size_type pos);           // 返回下标为pos的元素的引用;如果下标不正确,则抛出异常out_of_range
const_reference at(size_type pos) const;
            
void push_back(const T& x);            // 向容器末尾添加一个元素          
void pop_back();                       // 弹出容器中最后一个元素(容器必须非空)
 
// 注:下面的插入和删除操作将发生元素的移动(为了保持连续存储的性质),所以之前的迭代器可能失效
iterator insert(iterator it, const T& x = T());        // 在插入点元素之前插入元素(或者说在插入点插入元素)
void insert(iterator it, size_type n, const T& x);     // 注意迭代器可能不再有效(可能重新分配空间)
void insert(iterator it, const_iterator first, const_iterator last);
 
iterator erase(iterator it);           // 删除指定元素,并返回删除元素后一个元素的位置(如果无元素,返回end())
iterator erase(iterator first, iterator last); // 注意:删除元素后,删除点之后的元素对应的迭代器不再有效。
 
void clear() const;                    // 清空容器,相当于调用erase( begin(), end())
 
void assign(size_type n, const T& x = T());   // 赋值,用指定元素序列替换容器内所有元素
void assign(const_iterator first, const_iterator last);
 
const_iterator begin() const;          // 迭代序列
iterator begin();
const_iterator end() const;
iterator end();
 
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
const_reverse_iterator rend() const; 
reverse_iterator rend();
 
vector对象的比较(非成员函数)
 
   针对vector对象的比较有六个比较运算符:operator==、operator!=、operator<、operator<=、operator>、operator>=。
 
   其中,对于operator==和operator!=,如果vector对象拥有相同的元素个数,并且对应位置的元素全部相等,则两个vector对象相等;否则不等。
   对于operator<、operator<=、operator>、operator>=,采用字典排序策略比较。

注:其实只需要实现operator==和operator!=就可以了,其它可以根据这两个实现。因为,operator!= (lhs, rhs) 就是 !(lhs == rhs),operator<=(lhs, rhs) 就是 !(rhs < lhs),operator>(lhs, rhs) 就是 (rhs < lhs),operator>=(lhs, rhs) 就是 !(lhs, rhs)。
 
vector类的迭代器

   vector类的迭代器除了支持通用的前缀自增运算符外,还支持算术运算:it + n、it - n、it2 - it1。注意it2 - it1返回值为difference_type(signed类型)。
 
   注意,任何改变容器大小的操作都可能造成以前的迭代器失效。
 
应用示例
 

#include <iostream>
#include <cassert>
#include <vector>

using namespace std;

int main()
{
    vector<string> v(5, "hello");
    vector<string> v2(v.begin(), v.end());
    
    assert(== v2);
    
    cout<<"> Before operation"<<endl;
    for(vector<string>::const_iterator it = v.begin(); it < v.end(); ++it)
        cout<<*it<<endl;
    
    v.insert(v.begin() + 3, 4, "hello, world");
    cout<<"> After insert"<<endl;
    for(vector<string>::size_type i = 0; i < v.size(); ++i)
        cout<<v[i]<<endl;
    
    vector<string>::iterator it = v.erase(v.begin() + 3, v.begin() + 6);
    assert(*it == "hello, world");
    cout<<"> After erase"<<endl;
    for(vector<string>::size_type i = 0; i != v.size(); ++i)
        cout<<v[i]<<endl;
    
    assert(v.begin() + v.size() == v.end());
    assert(v.end() - v.size() == v.begin());
    assert(v.begin() - v.end() == -vector<string>::difference_type(v.size()));
    
    return 0;
}

程序说明:上面程序中用了三个循环输出容器中的元素,每个循环的遍历方式是不一样的。特别需要说明的是,第二个循环在条件判断中使用了size() 函数,而不是在循环之前先保存在变量中再使用。之所以这样做,有两个原因:其一,如果将来在修改程序时,在循环中修改了容器元素个数,这个循环仍然能很好 地工作,而如果先保存size()函数值就不正确了;其二,由于这些小函数(其实现只需要一条返回语句)基本上都被声明为inline,所以不需要考虑效率问题。

 原文地址 http://blog.chinaunix.net/u/18517/showart_232126.html


Vector

Vectors are a kind of sequence container. As such, their elements are ordered following a strict linear sequence.

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.

Vectors are good at:
  • Accessing individual elements by their position index (constant time).
  • Iterating over the elements in any order (linear time).
  • Add and remove elements from its end (constant amortized time).

Compared to arrays, they provide almost the same performance for these tasks, plus they have the ability to be easily resized. Although, they usually consume more memory than arrays when their capacity is handled automatically (this is in order to accommodate extra storage space for future growth).

Compared to the other base standard sequence containers (deques and lists), vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence. For operations that involve inserting or removing elements at positions other than the end, they perform worse than deques and lists, and have less consistent iterators and references than lists.

Internally, vectors -like all containers- have a size, which represents the amount of elements contained in the vector. But vectors, also have a capacity, which determines the amount of storage space they have allocated, and which can be either equal or greater than the actual size. The extra amount of storage allocated is not used, but is reserved for the vector to be used in the case it grows. This way, the vector does not have to reallocate storage on each occasion it grows, but only when this extra space is exhausted and a new element is inserted (which should only happen in logarithmic frequence in relation with its size).

Reallocations may be a costly operation in terms of performance, since they generally involve the entire storage space used by the vector to be copied to a new location. Therefore, whenever large increases in size are planned for a vector, it is recommended to explicitly indicate a capacity for the vector using member function vector::reserve.

In their implementation in the C++ Standard Template Library vectors take two template parameters:
 
template < class T, class Allocator = allocator<T> > class vector;

Where the template parameters have the following meanings:
  • T: Type of the elements.
  • Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.
In the reference for the vector member functions, these same names are assumed for the template parameters.

Member functions

(constructor)Construct vector (public member function)(destructor)Vector destructor (public member function)operator=Copy vector content (public member function )
Iterators:
beginReturn iterator to beginning (public member type)endReturn iterator to end (public member function)rbeginReturn reverse iterator to reverse beginning (public member function)rendReturn reverse iterator to reverse end (public member function)
Capacity:
sizeReturn size (public member function)max_sizeReturn maximum size (public member function )resizeChange size (public member function)capacityReturn size of allocated storage capacity (public member function)emptyTest whether vector is empty (public member function)reserveRequest a change in capacity (public member function)
Element access:
operator[]Access element (public member function)atAccess element (public member function)frontAccess first element (public member function)backAccess last element (public member function)
Modifiers:
assignAssign vector content (public member function)push_backAdd element at the end (public member function)pop_backDelete last element (public member function)insertInsert elements (public member function)eraseErase elements (public member function)swapSwap content (public member function)clearClear content (public member function)
Allocator:
get_allocatorGet allocator (public member function )

Member types

of template <class T, class Allocator=allocator<T> > class vector; 
member typedefinitionreferenceAllocator::referenceconst_referenceAllocator::const_referenceiteratorRandom access iteratorconst_iteratorConstant random access iteratorsize_typeUnsigned integral type (usually same as size_t)difference_typeSigned integral type (usually same as ptrdiff_t)value_typeTallocator_typeAllocatorpointerAllocator::pointerconst_pointerAllocator::const_pointerreverse_iteratorreverse_iterator<iterator>const_reverse_iteratorreverse_iterator<const_iterator>

Vector specialization: vector<bool>

The vector class template has a special template specialization for the bool type.

This specialization is provided to optimize for space allocation: In this template specialization, each element occupies only one bit (which is eight times less than the smallest type in C++: char).

The references to elements of a bool vector returned by the vector members are not references to bool objects, but a special member type which is a reference to a single bit, defined inside the vector<bool> class specialization as:


class vector< bool >::reference{friend class vector;reference(); // no public constructorpublic:~reference();operator bool() const; // convert to boolreference& operator=( const bool x ); // assign from boolreference& operator=( const reference& x ); // assign from bitvoid flip(); // flip bit value.}



For a similar container class to contain bits, but with a fixed size, see bitset.
原创粉丝点击