vector 扩容函数有哪些?
reserve 和 resize。
reserve如果预留的空间,不够则继续分配。
resize如果预留空间不够,也会继续分配内存,并且会调用构造函数。
#include<iostream>#include<vector>using namespace std;int main() {vector<int> v1(10);cout<<v1.size()<<endl; // 10v1.resize(20);cout<<v1.size()<<endl; // 20v1.reserve(30);cout<<v1.size()<<endl; // 20}
两个vector快速交换赋值
swap,直接交换容器内元素的地址,不会重新构造。
#include <iostream>#include <vector>int main (){std::vector<int> foo (3,100); // three ints with a value of 100std::vector<int> bar (5,200); // five ints with a value of 200std::cout << "foo contains:";for (unsigned i=0; i<foo.size(); i++)std::cout << ' ' << foo[i];std::cout << '\n';std::cout << "bar contains:";for (unsigned i=0; i<bar.size(); i++)std::cout << ' ' << bar[i];std::cout << '\n';cout<<&foo[0]<<endl;foo.swap(bar);std::cout << "foo contains:";for (unsigned i=0; i<foo.size(); i++)std::cout << ' ' << foo[i];std::std::cout << '\n';std::cout << "bar contains:";for (unsigned i=0; i<bar.size(); i++)std::cout << ' ' << bar[i];std::cout << '\n';std::cout<<&bar[0]<<endl;return 0;}
foo contains: 100 100 100bar contains: 200 200 200 200 2000x7ff040400020foo contains: 200 200 200 200 200bar contains: 100 100 1000x7ff040400020
