निम्नलिखित vector और array के बीच अंतर हैं −
- Vector एलिमेंट्स को स्टोर करने के लिए एक सीक्वेंशियल कंटेनर है और इंडेक्स आधारित नहीं है।
- Array एक ही प्रकार के एलिमेंट्स का एक फिक्स्ड-साइज़ सीक्वेंशियल कलेक्शन स्टोर करता है और यह इंडेक्स आधारित है।
- Vector प्रकृति में डायनामिक है इसलिए, एलिमेंट्स के इन्सर्शन के साथ आकार बढ़ता है।
- चूंकि array फिक्स्ड साइज़ का है, एक बार इनिशियलाइज़ होने के बाद इसका आकार बदला नहीं जा सकता।
- Vector अधिक मेमोरी घेरता है।
- Array मेमोरी-एफिशिएंट डेटा स्ट्रक्चर है।
- Vector एलिमेंट्स को एक्सेस करने में अधिक समय लेता है।
- Array एलिमेंट्स को उनकी लोकेशन की परवाह किए बिना कॉन्स्टेंट टाइम में एक्सेस करता है क्योंकि एलिमेंट्स कॉंटिगुअस मेमोरी एलोकेशन में व्यवस्थित होते हैं।
Vectors और arrays को निम्नलिखित सिंटैक्स के साथ डिक्लेयर किया जा सकता है −
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:: array:
उदाहरण कोड
#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