Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ลบรายการจาก Vector ด้วย erase()


สมมติว่าเรามีชุดข้อมูลใน vector ต้องลบรายการด้วยฟังก์ชัน erase() โดยใช้ index ฟังก์ชัน erase ไม่รับ index โดยตรง ต้องส่ง address ผ่าน v.begin()+index

เช่น v = [5,8,6,3,2,0,1,4] ลบ index 2, 6, 5 ผลลัพธ์: [5,8,3,2,0]

ขั้นตอน: ลบ index 2 → [5,8,3,2,0,1,4] ลบ index 6 (คือ 4) → [5,8,3,2,0,1] ลบ index 5 (คือ 1) → [5,8,3,2,0]

ขั้นตอนการแก้ปัญหา

  • v.erase(v.begin()+2)
  • v.erase(v.begin()+6)
  • v.erase(v.begin()+5)

ตัวอย่างโค้ด

#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){    vector<int> v = {5,8,6,3,2,0,1,4};    v.erase(v.begin()+2);    v.erase(v.begin()+6);    v.erase(v.begin()+5);    for(int i = 0; i<v.size(); i++) cout << v[i] << " "; }

อินพุต

{5,8,6,3,2,0,1,4}

เอาต์พุต

5 8 3 2 0