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

ข้อดีของ Vector เทียบกับ Array ใน C++

ที่นี่เราจะดูข้อดีและข้อเสียของ vector เทียบกับ array ใน C++

  • Vector เป็น template class เป็นคอนสตรัคต์เฉพาะ C++ Arrays เป็น built-in language construct มีอยู่ในหลายภาษา

  • Vectors ถูก implement เป็น dynamic arrays พร้อม list interface arrays สามารถ implement แบบ static หรือ dynamic ด้วย primitive datatypes

ตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int array[10]; // statically allocated array
    int* arr = new int[10]; // dynamically allocated array
    vector<int> vec;
}
  • ขนาด Array เป็นคงที่ เมื่อสร้าง array แล้ว ไม่สามารถเปลี่ยนขนาดได้ ขนาดของ Vector เป็น dynamic หากเพิ่มองค์ประกอบใหม่ ถ้าที่ว่างไม่พอ มันจะสร้างพื้นที่ใหม่และพื้นที่เพิ่มเติมบางส่วน

  • ถ้า arrays ถูกจัดสรรแบบ dynamic เราต้อง deallocate เอง แต่ใน vector ไม่ต้อง deallocate เอง มัน deallocate เองอัตโนมัติเมื่อตัวแปรออกจากขอบเขต (scope)

ตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int* arr = new int[10]; // dynamically allocated array
    delete(arr); // deallocate เอง
    vector<int> vec; // จะถูก deallocate อัตโนมัติเมื่อตัวแปรออกจาก scope
}
  • ถ้าต้องการขนาดของ dynamically allocated array เราไม่สามารถหาได้ง่าย สำหรับ vectors เราสามารถหาขนาดได้ใน constant time

  • ถ้าต้องการส่ง array ผ่านพารามิเตอร์ฟังก์ชัน เราต้องส่งตัวแปรอื่นสำหรับขนาด/ความยาว ถ้าส่ง vector ไม่ต้องส่งตัวแปรอื่น

  • เราไม่สามารถ return array ได้ เว้นแต่ใช้ dynamically allocated new array แต่นำ vector ส่งคืนจากฟังก์ชันได้