Arrays aur Vectors
Ek C-style array ka size compile time par fixed hota hai aur grow karne ka koi built-in tarika nahi hota. sizeof(array) / sizeof(array[0]) iski length calculate karne ka classic (thoda clunky hi sahi) idiom hai, kyunki ek array runtime par apna size track nahi karta.
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
cout << "numbers[2] = " << numbers[2] << endl;
cout << "size = " << sizeof(numbers) / sizeof(numbers[0]) << endl;
return 0;
}numbers[2] = 3 size = 5
std::vector
std::vector C++ ka primary growable collection hai — yeh apna khud ka heap-allocated storage manage karta hai aur jab aap elements push_back karte ho to khud ko automatically resize kar leta hai. Yeh ek template hai, isliye vector<int> aur vector<string> dono valid, type-safe instantiations hain.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3};
numbers.push_back(4);
numbers.push_back(5);
for (int n : numbers) {
cout << n << " ";
}
cout << endl;
cout << "size = " << numbers.size() << endl;
return 0;
}1 2 3 4 5 size = 5
Aage: strings — std::string, ek real owned, mutable string type.
Practice exercise
Ek vector<int> numbers = {4, 8, 15, 16} diya gaya hai, ek range-based for loop se iske saare elements sum karo aur total print karo.