c++的vector容器的基本操作

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
using namespace std;
void printvector(const vector& vec)
{
    for (vector::const_iterator it = vec.begin(); it != vec.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}
void printRvector(vector& vec)
{
    for (vector::reverse_iterator it = vec.rbegin(); it != vec.rend(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}
void test01()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    vector v(arr, arr + sizeof(arr) / sizeof(arr[0])); // 修正计算数组元素个数的方法
    printvector(v);
    printRvector(v);
    vectorv1(10, 6);//十个六
    printvector(v1);
}
//常用的赋值操作
void test02()
{
    vectorv1;
    v1.assign(10, 6);
    vectorv2;
    v2.push_back(10);
    v2.push_back(20);
    printvector(v1);
    printvector(v2);
    cout << "----------"<v2;
    v2.push_back(10);
    v2.push_back(20);
    cout << "size:" << v2.size()<< endl;
    v2.resize(5);
    cout << "size:" << v2.size() << endl;
    printvector(v2);
    v2.reserve(20);
    cout << "size:" << v2.size() << endl;
    printvector(v2);
    cout << "capacity:" << v2.capacity() << endl;
    //cout<v;
    for (int i = 0; i < 100001; i++)
    {
        v.push_back(i);
    }
    cout << "capacity:" << v.capacity() << endl;
    cout << "size:" << v.size() << endl;
    cout << "-------"<v2(v);
    cout << "capacity:" << v2.capacity() << endl;
    cout << "size:" << v2.size() << endl;
    cout << "-------" << endl;
    vector(v).swap(v);//(v)匿名对象和v对象交换
    cout << "capacity:" << v.capacity() << endl;
    cout << "size:" << v.size() << endl;
    cout << "-------" << endl;

}
//数据存储
void test05()
{
    vectorv;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << v.front() << endl;
    cout << v.back() << endl;
    v.front() = 100;
    v.back() = 300;
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
}
//插入删除
void test06()
{
    vectorv;
    for (int i = 0; i < 5; i++)
    {
        v.push_back(i + 1);
    }
    printvector(v);
    v.insert(v.begin() + 1, 100);
    printvector(v);
    v.insert(v.begin() + 1,2, 200);
    printvector(v);
    v.pop_back();
    printvector(v);
    v.erase(v.begin());
    printvector(v);
    v.erase(v.end() - 1);
    printvector(v);
    v.erase(v.begin()+1 , v.end()-1 );
    printvector(v);
    v.clear();
    printvector(v);
    
}
void test07()
{
    vectorv;
    for (int i = 0; i < 5; i++)
    {
        v.push_back(i + 1);
    }
    cout << *(v.end()-1) << endl;
}
int main()
{
	test07();
	system("pause");
	return EXIT_SUCCESS;
}

你可能感兴趣的:(c++,算法,开发语言)