Container Classes & Iterators

Introduction

C++ में data को efficiently store और manage करने के लिए Standard Template Library (STL) का उपयोग किया जाता है। STL में कई प्रकार के container classes उपलब्ध होते हैं, जिनका उपयोग data को अलग-अलग तरीकों से store करने के लिए किया जाता है।

इन containers के साथ काम करने के लिए iterators का उपयोग किया जाता है, जो elements को traverse (एक-एक करके access) करने का कार्य करते हैं। Container classes और iterators मिलकर data handling को सरल, flexible और efficient बनाते हैं।

Definition

Container Classes

Container classes वे classes होती हैं जो data (elements) को store और organize करने के लिए उपयोग की जाती हैं। ये STL का हिस्सा होती हैं।

Iterators

Iterators ऐसे objects होते हैं जिनका उपयोग container के elements को access और traverse करने के लिए किया जाता है।

Container Classes के प्रकार

1. Sequence Containers

इनमें data sequential order में store होता है।

उदाहरण:

  • vector
  • list
  • deque

2. Associative Containers

इनमें data key-value pair के रूप में store होता है।

उदाहरण:

  • set
  • map

3. Container Adapters

ये अन्य containers के ऊपर आधारित होते हैं।

उदाहरण:

  • stack
  • queue

Iterator का Concept

Iterator एक pointer की तरह कार्य करता है, जो container के elements को point करता है और उन्हें access करने में मदद करता है।

Basic Syntax (Iterator)

containerType::iterator it;

Example (vector और iterator)

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

int main() {
vector<int> v = {10, 20, 30};

vector<int>::iterator it;

for (it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}

return 0;
}

Output:

10 20 30

Working को समझना

  • vector<int> v → container है
  • it → iterator है
  • v.begin() → first element को point करता है
  • v.end() → last के बाद वाले position को point करता है
  • *it → value access करता है

Common Iterator Functions

  • begin() → first element
  • end() → last के बाद
  • ++ → next element पर जाना
  • * → value access करना

Container Classes के लाभ

  • Data को efficiently store करते हैं
  • Dynamic size support करते हैं
  • Built-in functions उपलब्ध होते हैं
  • Code को सरल और reusable बनाते हैं

Iterators के लाभ

  • Data traversal को आसान बनाते हैं
  • Pointer जैसा behavior देते हैं
  • STL algorithms के साथ काम करते हैं

निष्कर्ष

Container classes और iterators C++ के STL का महत्वपूर्ण हिस्सा हैं, जो data को store और access करने के लिए powerful tools प्रदान करते हैं। इनके उपयोग से programming अधिक efficient, flexible और organized बनती है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top