C++ vector按照位置刪除元素、插入元素

刪除一個元素

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

刪除一串元素

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);

插入元素

// Program below illustrates the 
// vector::insert() function 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // initialising the vector 
    vector<int> vec = { 10, 20, 30, 40 }; 
  
    // inserts 3 at front 
    auto it = vec.insert(vec.begin(), 3); 
    // inserts 2 at front 
    vec.insert(it, 2); 
  
    int i = 2; 
    // inserts 7 at i-th index 
    it = vec.insert(vec.begin() + i, 7); 
  
    cout << "The vector elements are: "; 
    for (auto it = vec.begin(); it != vec.end(); ++it) 
        cout << *it << " "; 
  
    return 0; 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章