Modern C++ और C Alternatives

STL Containers और Algorithms

Manual array processing की composable algorithms से तुलना करें।

STL Containers और Algorithms क्या है?

C++ algorithms iterator ranges पर चलकर operation को storage से अलग करते हैं।

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

  • पहले C mechanism समझें।
  • Ownership के लिए RAII और value semantics उपयोग करें।
  • Macros और casts से अधिक type-safe abstractions चुनें।

C और C++ code examples

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

int main(void) {
    int values[] = {3, 8, 2, 7, 6};
    int even[5];
    int count = 0;
    int sum = 0;
    for (int index = 0; index < 5; ++index) {
        if (values[index] % 2 == 0) {
            even[count++] = values[index];
        }
    }
    for (int index = 0; index < count; ++index) {
        sum += even[index];
    }
    printf("count=%d sum=%d\n", count, sum);
}
अपेक्षित output
count=3 sum=16
C++
कोड चलाएँ →
main.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

int main() {
    std::vector values{3, 8, 2, 7, 6};
    std::vector<int> even;
    std::copy_if(values.begin(), values.end(),
                 std::back_inserter(even),
                 [](int value) { return value % 2 == 0; });
    std::cout << "count=" << even.size()
              << " sum="
              << std::accumulate(even.begin(), even.end(), 0) << '\n';
}
अपेक्षित output
count=3 sum=16

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

C loops और capacity स्पष्ट रखता है; C++ copy_if, accumulate और vector reusable ढंग से जोड़ता है।

C

C prefixes, callbacks, macros और context structs उपयोग करता है।

C++

Language scoped और type-safe abstractions देता है।

अभ्यास

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

  • पहले C mechanism लिखें।
  • Manual cleanup को RAII से बदलें।
  • Allocation और virtual dispatch जाँचें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज