C++ vector使用实例

C++ vector 

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    vector<string> vec_str;
    vec_str.reserve(6);

    vec_str.push_back("C++,");
    vec_str.insert(vec_str.end(), {"test1","test2","test3","test4"});

    copy(vec_str.cbegin(), vec_str.cend(), ostream_iterator<string>(cout, "  "));
    cout << endl;


    cout << "max_size:" << vec_str.max_size() << endl;
    cout << "size:" << vec_str.size() << endl;
    cout << "capacity:" << vec_str.capacity() << endl;

    swap(vec_str[1], vec_str[3]);

    vec_str.insert(find(vec_str.begin(),vec_str.end(),"test1"),"TEST");
    vec_str.back() = "Java";
    copy(vec_str.cbegin(),vec_str.cend(),ostream_iterator<string>(cout,"  "));
    cout << endl;

    cout << "size:" << vec_str.size() << endl;
    cout << "capacity:" << vec_str.capacity() << endl;

    vec_str.pop_back();
    vec_str.pop_back();
    vec_str.shrink_to_fit();

    cout << "size:" << vec_str.size() << endl;
    cout << "capacity:" << vec_str.capacity() << endl;

    system("pause");
    return 0;
}

C++, test1 test2 test3 test4
max_size:461168601842738790
size:5
capacity:6
C++, test3 test2 TEST test1 Java
size:6
capacity:6
size:4
capacity:4
请按任意键继续. .

原文地址:https://www.cnblogs.com/herd/p/12045674.html