STL Containers और Algorithms
C++ algorithms iterator ranges पर चलकर operation को storage से अलग करते हैं।
STL Containers और Algorithms क्या है?
C++ algorithms iterator ranges पर चलकर operation को storage से अलग करते हैं।
Manual array processing की composable algorithms से तुलना करें।
महत्वपूर्ण बातें
- पहले C mechanism समझें।
- Ownership के लिए RAII और value semantics उपयोग करें।
- Macros और casts से अधिक type-safe abstractions चुनें।
C और C++ code examples
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);
}
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';
}
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 जाँचें।