ต่อไปนี้เป็นข้อแตกต่างระหว่างเวกเตอร์และอาร์เรย์ -
- เวกเตอร์คือคอนเทนเนอร์แบบต่อเนื่องสำหรับจัดเก็บองค์ประกอบและไม่ใช่แบบอิงดัชนี
- อาร์เรย์จัดเก็บคอลเล็กชันตามลำดับขนาดคงที่ขององค์ประกอบประเภทเดียวกันและอิงตามดัชนี
- เวกเตอร์มีลักษณะแบบไดนามิก ดังนั้น ขนาดจะเพิ่มขึ้นเมื่อมีการแทรกองค์ประกอบ
- เนื่องจากอาร์เรย์มีขนาดคงที่ เมื่อเริ่มต้นแล้วจะไม่สามารถปรับขนาดได้
- เวกเตอร์ใช้หน่วยความจำมากขึ้น
- อาร์เรย์คือโครงสร้างข้อมูลที่มีประสิทธิภาพของหน่วยความจำ
- เวกเตอร์ใช้เวลาในการเข้าถึงองค์ประกอบมากขึ้น
- องค์ประกอบการเข้าถึงอาร์เรย์ในเวลาคงที่โดยไม่คำนึงถึงตำแหน่งขององค์ประกอบ เนื่องจากองค์ประกอบต่างๆ ถูกจัดเรียงในการจัดสรรหน่วยความจำที่ต่อเนื่องกัน
เวกเตอร์และอาร์เรย์สามารถประกาศได้โดยใช้รูปแบบดังนี้ -
Vector declaration:vector<datatype>array name;
Array declaration:type array_name[array_size];
Vector initialization:vector<datatype>array name={values};
Array initialization:datatype arrayname[arraysize] = {values}; std::vector:
โค้ดตัวอย่าง
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>>v{ { 4, 5, 3 }, { 2, 7, 6 }, { 3, 2, 1 ,10 } };
cout<<"the 2D vector is:"<<endl;
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++)
cout << v[i][j] << " ";
cout << endl;
}
return 0;
} ผลลัพธ์
the 2D vector is: 4 5 3 2 7 6 3 2 1 10
std::อาร์เรย์:
โค้ดตัวอย่าง
#include<iostream>
#include<array>
using namespace std;
int main() {
array<int,4>a = {10, 20, 30, 40};
cout << "The size of array is : ";
//size of the array using size()
cout << a.size() << endl;
//maximum no of elements of the array
cout << "Maximum number of elements array can hold is : ";
cout << a.max_size() << endl;
// Printing array elements using at()
cout << "The array elements are (using at()) : ";
for ( int i=0; i<4; i++)
cout << a.at(i) << " ";
cout << endl;
// Filling array with 1
a.fill(1);
// Displaying array after filling
cout << "Array after filling operation is : ";
for ( int i=0; i<4; i++)
cout << a[i] << " ";
return 0;
} ผลลัพธ์
The size of array is : 4 Maximum number of elements array can hold is : 4 The array elements are (using at()) : 10 20 30 40 Array after filling operation is : 1 1 1 1