首页 > 代码库 > vector 基础2

vector 基础2

size         :返回有效元素个数

max_size     :返回 vector 支持的最大元素个数

resize       :改变有效元素的个数

capacity      :返回当前可使用的最大元素内存块数(即存储容量)

empty       :判断是否为空

reserve       :请求改变存储容量

shrik_to_fit     :请求移除未使用的存储空间

std::vector<int> foo;    for (int i = 0; i<100; i++) foo.push_back(i);    std::cout << "size: " << (int)foo.size() << \n;    std::cout << "capacity: " << (int)foo.capacity() << \n;    std::cout << "max_size: " << (int)foo.max_size() << \n;    foo.resize(5);    foo.resize(8, 100);    foo.resize(12);    for (int i = 0; i < foo.size(); i++)        std::cout <<   << foo[i];    std::cout << std::endl;    int sum(0);    while (!foo.empty())    {        sum += foo.back();        foo.pop_back();    }    std::cout << "total: " << sum << \n;    foo.reserve(200); //设置最小容量,返回值大于等于这个值    std::cout << "capacity: " << (int)foo.capacity() << \n; //200,如果设置100,这里是141    foo.resize(5);    foo.shrink_to_fit(); //请求移除不使用的空间    std::cout << "capacity: " << (int)foo.capacity() << \n; //5

[] at

front    访问第一个元素

back    访问最后一个元素

data    返回当前向量内部数组的指针

#include <iostream>#include <vector>int main(){    std::vector<int> foo(5);    int* p = foo.data();    *p = 10;    ++p;    *p = 20;    p[2] = 100;    std::cout << "foo.front() is now " << foo.front() << std::endl;    std::cout << "foo:";    for (unsigned i = 0; i<foo.size(); ++i)        std::cout <<   << foo[i];    std::cout << std::endl;    return 0;}

 

vector 基础2