C/C++ Data Structures

Dynamic Array और std::vector

Dynamic array logical size को capacity से अलग रखकर geometrically grow करता है।

Dynamic Array और std::vector क्या है?

Dynamic array logical size को capacity से अलग रखकर geometrically grow करता है।

Values append होने पर contiguous storage बढ़ाएँ।

महत्वपूर्ण बातें

  • Operations से पहले invariants तय करें।
  • Empty, full और allocation-failure cases संभालें।
  • Complexity और ownership साथ मापें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t size = 0, capacity = 2;
    int *values = malloc(capacity * sizeof *values);
    if (!values) return 1;
    for (int value = 1; value <= 5; ++value) {
        if (size == capacity) {
            capacity *= 2;
            int *grown = realloc(values, capacity * sizeof *values);
            if (!grown) {
                free(values);
                return 1;
            }
            values = grown;
        }
        values[size++] = value * value;
    }
    printf("size=%zu capacity=%zu last=%d\n",
           size, capacity, values[size - 1]);
    free(values);
}
अपेक्षित output
size=5 capacity=8 last=25
C++
कोड चलाएँ →
main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values;
    for (int value = 1; value <= 5; ++value) {
        values.push_back(value * value);
    }
    std::cout << "size=" << values.size()
              << " last=" << values.back() << '\n';
}
अपेक्षित output
size=5 last=25

C और C++ की तुलना

C realloc failure और capacity संभालता है; std::vector growth, destruction, iterators और exception safety package करता है।

C

Structures और operations अलग, allocation स्पष्ट होता है।

C++

Classes और containers invariants और resources manage करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Empty और capacity boundary tests जोड़ें।
  • Cleanup लागू कर leaks जाँचें।
  • Standard container से तुलना करें।