Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔴 Advanced  ·  Lesson 54

Vector in C++ STL

C++ में std::vector क्या है?

std::vector<T> growable sequence container है। Ordinary types में elements contiguous रहते हैं, array जैसी indexing मिलती है और memory/lifetime automatic manage होती है।

#include <vector>
std::vector<int> marks{78,91,84};
PropertyGuarantee
Index accessO(1)
End insertionAmortized O(1)
Middle insert/eraseO(n)
Storagevector<bool> छोड़कर contiguous
General growable sequence में vector से start करें, जब तक ordering/insertion/handle stability की requirement दूसरा container न मांगे। vector vs map भी देखें।

Vector Create और Initialize करें

std::vector<int> empty;
std::vector<int> five_zeros(5);
std::vector<int> four_sevens(4,7);
std::vector<int> values{5,10,15};
std::vector copy=values;

vector<int>(5,10) पांच बार 10 रखता है, जबकि {5,10} दो values रखता है। Related fields के parallel vectors के बजाय record रखें:

struct Student{std::string name;int mark;};
std::vector<Student> students{{"Aman",78},{"Sara",91}};

Direct headers include करें और headers/examples में using namespace std; avoid करें।

Elements Safely Access करें

MethodUse
v[i]No bounds check
v.at(i)Invalid पर out_of_range
front()First, vector non-empty हो
back()Last, vector non-empty हो
data()Contiguous range pointer
if(!marks.empty()) std::cout<<marks.front();
try{ std::cout<<marks.at(user_index); }
catch(const std::out_of_range&){
 std::cerr<<"Invalid index\n";
}

Last valid index non-empty vector में size()-1 है। Unsigned reverse loop में underflow से बचें।

Essential Vector Methods

MethodEffect
push_backEnd पर value
emplace_backEnd पर construct
pop_backLast remove; empty नहीं
insertPosition से पहले insert
eraseElement/range remove
clearAll elements destroy, capacity रह सकती है
swapContents/capacity exchange
marks.push_back(96);
marks.emplace_back(88);
marks.insert(marks.begin()+1,80);
marks.erase(marks.begin()+2);
auto removed=std::erase_if(marks,
 [](int m){return m<40;}); // C++20

pop_back value return नहीं करता। Already-created object में move और emplace के बीच automatic speed assumption न करें।

Size, Capacity, reserve और resize

std::vector<int> values;
values.reserve(100); // size 0
values.push_back(7); // size 1
values.resize(4);    // 7 0 0 0
  • size(): live elements।
  • capacity(): reallocation से पहले storage limit।
  • reserve(n): capacity request, size unchanged।
  • resize(n): element count change।
  • shrink_to_fit(): non-binding request।
reserve(100) के बाद values[50] invalid है क्योंकि capacity size नहीं है।

Known final size पर एक बार reserve उपयोगी है; हर push से पहले reserve growth strategy खराब कर सकता है। Doubling guaranteed नहीं है।

Iteration और Invalidation

for(int mark:marks) std::cout<<mark<<' ';
for(const Student& s:students) std::cout<<s.name;
std::sort(marks.begin(),marks.end());
  • Reallocation सभी iterators/pointers/references invalid करती है।
  • No reallocation में insert point से आगे handles invalid।
  • Erase position और उसके बाद handles invalid।
  • reserve केवल reallocation होने पर invalidates।
auto it=marks.begin();
marks.push_back(99); // it invalid हो सकता है
it=marks.begin();

iterators और algorithms आगे पढ़ें।

Complete Practical Program और Output

std::vector<int> marks;
marks.reserve(6);
for(int m:{72,88,65,91,88}) marks.push_back(m);
int total=std::accumulate(marks.begin(),marks.end(),0);
int highest=*std::max_element(marks.begin(),marks.end());
std::sort(marks.begin(),marks.end());
Sorted: 65 72 88 88 91 Average: 80.8 Highest: 91

Reserve ने elements नहीं बनाए, केवल insertion के लिए capacity दी। Total 404 है और floating-point division से average 80.8 आया।

Mistakes, Practice और Review

MistakeCorrection
Index == sizeOut of range
reserve के बाद indexpush/resize करें
Empty front/back/popempty check
Growth के बाद iteratorReacquire
clear frees capacityCapacity रह सकती है
Raw owning pointersValues/smart owners

Practice: duplicates remove करें; Student records mark के अनुसार sort करें; reserve से पहले/बाद size-capacity दिखाएं; negative values erase करें; at और [] compare करें।

  1. Header included?
  2. Index valid?
  3. Empty case?
  4. Size/capacity clear?
  5. Invalidation checked?
  6. Algorithm preconditions valid?

Authoritative संदर्भ

Complexity, reserve/resize और invalidation current working draft से verified हैं। Complete STL guide भी पढ़ें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

C++ में vector क्या है?
std::vector contiguous sequence container है; vector specialization exception है। यह O(1) indexed access और end पर amortized O(1) insertion देता है।
vector size और capacity में क्या अंतर है?
size constructed elements की संख्या है। capacity बताती है कि current storage reallocation से पहले कितने elements रख सकती है। Capacity size से अधिक हो सकती है।
reserve और resize में क्या अंतर है?
reserve elements बनाए बिना capacity request करता है और size नहीं बदलता। resize elements की संख्या बदलकर construction या trailing removal करता है।
operator[] या at() में क्या चुनें?
operator[] bounds check नहीं करता। at() invalid index पर std::out_of_range throw करता है। External index में at() और proven valid index में operator[] लें।
vector iterators कब invalidate होते हैं?
Reallocation सभी element iterators, pointers और references invalidate करती है। Reallocation न हो तो insertion point से आगे और erase position से आगे के handles invalid होते हैं।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topiclist and deque in STL आपकी प्रगति: 54 / 81 (67%) · Lesson 55 / 81 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें