STL and Modern C++ Basics
The Standard Template Library provides ready-made containers and algorithms. Modern C++ also includes language features that make code shorter, clearer, and safer.
Using vector
Dynamic collection with vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6);
for (int number : numbers)
{
cout << number << " ";
}
return 0;
}Using auto
Automatic type deduction
auto quantity = 10; // int
auto price = 19.95; // double
auto title = string("C++ Tutorial");Prefer Clear and Safe Modern Code
- Use
vectorinstead of manually managed dynamic arrays for most beginner tasks. - Use range-based loops when you need each element.
- Use
constwhen a value should not change. - Use
nullptrinstead of older null-pointer constants.
Practice task
Create a vector of five marks, add one more mark with push_back(), and display all values.
Lesson Summary
Get started with vector, range-based loops, auto, and safer modern syntax.