c++STL vector存儲插入刪除大小


size()  //返回容器中元素的個數

empty() //判斷容器是否為空

resize(int num) //重新指定容器的長度num,容器變長,則以默認值填充新位置,如果容器變短,則末尾超出容器長度的元素被刪除

resize(int num,elem) //重新制定容器的長度為num,若容器變長,則以elem值填充位置,如果容器便短,則刪除超出長度的元素

capacity() 容器的容量

reserve(int len) //容器預留len個元素長度,預留位置不初始化,元素不可訪問

#include <iostream>
#include <vector>
using namespace std;
void show(vector<int> &v){
    for(vector<int>::const_iterator it =v.begin();it != v.end();it ++){ //迭代器的本質是地址
        cout << *it<<" ";
    }
    cout<<endl;
};
void test01(){
    int arry[] ={10,20,30,40,50,60,70};
    vector<int> v1(arry,arry+sizeof(arry)/sizeof(arry[0]));
    cout<<"元素個數:"<<v1.size()<<endl;
    if (v1.empty()){
        cout<<"vector是空"<<endl;}
    else cout<<"vector不為空"<<endl;
    v1.resize(10); //resize()中的int類型是指元素個數
    show(v1);
    v1.resize(15,11);
    show(v1);
    cout<<"容器的容量"<<v1.capacity()<<endl;
    v1.reserve(30); //size一定小於容量
    show(v1);
    cout<<"容器的容量"<<v1.capacity()<<endl;

}


int main() {

    test01();
    return 0;
}

at(int idx)  返回idx的索引數據,如果越界拋出out_of_range異常

operator[] 返回索引idx所指的數據,越界時,運行直接報錯

front() 返回容器中第一個元素

back()返回容器中最后一個元素

#include <iostream>
#include <vector>
#include<cstring>
using namespace std;
void test(){
    int arry[] = {0,1,2,3,4};
    vector<int> v(arry,arry+sizeof(arry)/sizeof(arry[0]));
    int a = v.at(9);
    cout<<a<<endl;
    cout<<v.front()<<"  ";
    cout<<v.back()<<endl;
    cout<<"________"<<endl;
    a = v[9];
    cout<<a<<endl;
}
int main() {
    try{
    test();}
    catch (out_of_range){
        cout<<"out of range";
    }
    return 0;
}

insert(const_iterator pos,int count,ele);   從pos插入count個ele

push_back(ele);  尾部插入元素

pop_back(); 刪除最后一個元素

erase(const_iterator start,const_iterator end);刪除迭代器 start-end之間的元素

clear() ; 清除所有元素

#include <iostream>
#include <vector>
using namespace std;
void show(vector<int> &v){
    for(vector<int>::const_iterator it =v.begin();it != v.end();it ++){ //迭代器的本質是地址
        cout << *it<<" ";
    }
    cout<<endl;
};
void test01(){
    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.insert(v.begin(),30);//從頭部插入一個元素
    show(v);
    v.insert(v.end(),40);//從尾部插入一個元素
    show(v);
    v.insert(v.begin()+2,100);//可以隨機訪問的類型,可以采用+元素個數來偏移
    show(v);
    v.erase(v.begin());//刪除第一個元素
    show(v);
    v.erase(v.begin()+2,v.end());//刪除從頭部的兩個元素
    show(v);
    v.clear();
    cout<<"v.size = " << v.size()<<endl;
}
int main() {
    test01();
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM