STL基本操作

一、序列式容器

1、初始化方式

创建无参对象
vector<int> vec;

传count个value
vector<int> vec(10, 2);

迭代器范围
int arr[10] = {1, 3, 5, 7, 9,  8, 6, 4, 2, 0};
vector<int> vec(arr, arr + 10);

拷贝构造与移动构造
vector<int> vec (10, 2);
vector<int> vec2(vec);

大括号形式
vector<int>vec = {1, 3, 5, 7, 9,  8};

2、常用赋值操作

assign(begin, end);
assign(n, elem);
vector &operator=(const vector &vec);

3、大小操作

size();
empty();
resize(int num);
resize(int num, elem); //重新指定容器长度为10,用elem填充新位置
capacity();
reserve(int len);    //预留空间

4、vector数据存取操作

at(int idx); //返回索引idx所指的数据
operator[];
front();        //返回容器中第一个元素
back();    //返回容器中最后一个元素

5、插入与删除

iterator insert( const_iterator pos, const T& value );
void push_back( const T& value );
void pop_back();
iterator erase( iterator pos );
iterator erase( iterator first, iterator last );
void clear();    //Erases all elements from the container.

 三种容器都支持在尾部插入与删除,list与deque支持头部插入与删除,vector不支持

6、遍历

vector<int>::iterator itBegin = vec.begin();
    vector<int>::iterator itEnd = vec.end();

    while (itBegin != itEnd) {
        cout << *itBegin << endl;
        itBegin++;
    }

    for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
        cout << *it << endl;
    }

    for_each(vec.begin(), vec.end(), print);

 7、容器元素互换

swap 实现两个容器内元素进行互换,可用来收缩内存

void test4() {
    vector<int> vec;
    for (int i = 0; i < 100000; i++) {
        vec.push_back(i);
    }

    cout << "size = " << vec.size() << endl;
    cout << "capacity = " << vec.capacity() << endl; 

    vec.resize(3);

    vector<int>(vec).swap(vec);

    cout << "size = " << vec.size() << endl;
    cout << "capacity = " << vec.capacity() << endl;
}

 

 

posted @ 2023-04-04 11:31  晚安地球人1  阅读(52)  评论(0)    收藏  举报