This walkthrough covers the practical C++ subset used in coursework and competitive programming: iostream, vectors and strings, references, structs and classes, and the STL algorithms.
1. iostream instead of printf
cin and cout handle types automatically, so there are no format specifiers to get wrong. '\n' is cheaper than endl because endl also flushes.
#include <iostream>
using namespace std;
int main() {
int marks = 87;
cout << "Marks: " << marks << "\n";
return 0;
}
2. Prefer vector and string over raw arrays
vector grows on demand and knows its own size; string handles memory for you. Together they remove most memory bugs beginners hit in C.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {5, 3, 9};
v.push_back(1);
for (int x : v) cout << x << " ";
cout << "\nsize: " << v.size() << "\n";
return 0;
}
3. Pass by reference to avoid copies
A & parameter lets the function work on the caller's object. Add const when the function only reads it — that is the standard signature for large containers.
#include <iostream>
#include <vector>
using namespace std;
int sum(const vector<int> &v) {
int t = 0;
for (int x : v) t += x;
return t;
}
int main() { cout << sum({1, 2, 3}) << "\n"; }
4. Group data with structs and classes
struct and class differ only in default access. Constructors initialise members, and member functions keep the related logic beside the data.
#include <iostream>
using namespace std;
struct Student {
string name;
int marks;
bool passed() const { return marks >= 50; }
};
int main() {
Student s{"Diya", 72};
cout << s.name << " " << s.passed() << "\n";
}
5. Let the STL do the work
sort, find, count, accumulate and max_element cover most of what you would otherwise hand-write, and they are already optimised.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {4, 1, 9, 2};
sort(v.begin(), v.end());
cout << *max_element(v.begin(), v.end()) << "\n";
for (int x : v) cout << x << " ";
}