C++ STL vector容器的插入和删除

使用swap函数交换两个vector容器中的值
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void OutToScreen(int& Ele){
    cout<<Ele<<",";
}

int main()
{
    vector<int> ci,cd;
    for(int i=0;i<10;++i){
        ci.push_back(i);
        cd.push_back(i*3);
    }
    cout<<"vector-ci-below: "<<endl;
    for_each(ci.begin(),ci.end(),OutToScreen);
    cout<<endl;
    cout<<"vector-cd-below: "<<endl;
    for_each(cd.begin(),cd.end(),OutToScreen);
    cout<<endl;
    cout<<"-------swap-------"<<endl;
    ci.swap(cd);
    cout<<"vector-ci-below: "<<endl;
    for_each(ci.begin(),ci.end(),OutToScreen);
    cout<<endl;
    cout<<"vector-cd-below: "<<endl;
    for_each(cd.begin(),cd.end(),OutToScreen);
    cout<<endl;
    return 0;
}

vector中插入元素
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void OutToScreen(int& Ele){
    cout<<Ele<<",";
}

int main()
{
    vector<int> myvt;
    for(int i=0;i<10;++i){
        myvt.push_back(i);
    }
    myvt.insert(myvt.begin(),-1);
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    myvt.insert(myvt.end(),-2);
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    vector<int> vt2;
    vt2.push_back(-8);
    vt2.push_back(-9);
    //插入多个数值
    myvt.insert(myvt.end(),vt2.begin(),vt2.end());
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    //插入3个0
    myvt.insert(myvt.begin(),3,0);
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    return 0;
}

从容器vector中删除元素
//vector元素的删除
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void OutToScreen(int& Ele){
    cout<<Ele<<",";
}

int main()
{
    vector<int> myvt;
    for(int i=0;i<10;++i)
        myvt.push_back(i);
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    cout<<"--------------------"<<endl;
    while(!myvt.empty()){
        myvt.pop_back(); //弹出向量
        for_each(myvt.begin(),myvt.end(),OutToScreen);
        cout<<endl;
    }
    myvt.clear();
    for(int j=0;j<10;++j){
        myvt.push_back(j);
    }
    for_each(myvt.begin(),myvt.end(),OutToScreen);
    cout<<endl;
    cout<<"--------------------"<<endl;
    while(!myvt.empty()){
        myvt.erase(myvt.begin());
        for_each(myvt.begin(),myvt.end(),OutToScreen);
        cout<<endl;
    }
    return 0;
}






猜你喜欢

转载自blog.csdn.net/ibelievesunshine/article/details/80216610
今日推荐