SC 428 · Introduction to C++ and the STL
// Lecture 2
Control Flow, Complexity,
Arrays and Vectors
Kalp Shah · IIT Gandhinagar · 27 October 2026
Before we start
Mark your attendance
Scan the QR code with your phone.
Today
Six topics, each followed by practice
01
Decisions
if / else, else-if ladders, switch
02
Loops
for, while, break, continue, nested loops, patterns
03
Big-O
Growth rates, counting loops, fast I/O
04
Arrays
1D and 2D, indexing, out-of-bounds, limits
05
Vectors
Operations and their costs, 2D vectors, references, pairs
06
STL helpers
reverse, min/max_element, accumulate, count, find, swap
SC 428 · Lecture 2 · Practice slides have a blue-grey background
01
Decisions
if / else · else-if ladders · switch
Decisions
if and else choose one of two paths
int marks;
cin >> marks;
if (marks >= 40) {
cout << "Pass\n";
} else {
cout << "Fail\n";
}
- The condition is converted to bool: 0 is false, every other value is true.
- The else branch is optional and runs only when the condition is false.
- Braces group statements. Use them even for one line.
Operators you will use
== != < <= > >=
&& (and) || (or) ! (not)
SC 428 · Lecture 2 · Decisions
Decisions
An else-if ladder stops at the first true test
Correct: strictest test first
char grade;
if (marks >= 90) grade = 'A';
else if (marks >= 75) grade = 'B';
else if (marks >= 60) grade = 'C';
else if (marks >= 40) grade = 'D';
else grade = 'F';
Bug: loosest test first
if (marks >= 40) grade = 'D';
else if (marks >= 60) grade = 'C';
else if (marks >= 75) grade = 'B';
else if (marks >= 90) grade = 'A';
else grade = 'F';
// 95 marks -> 'D'
Conditions are checked top to bottom and only one branch runs, so order the tests from most specific to least specific.
SC 428 · Lecture 2 · Decisions
Decisions
Four things to know about conditions
= is not ==
if (x = 5) { ... }
// assigns 5, then tests 5: always true
No braces, one statement
if (x > 0)
cout << "positive\n";
cout << "done\n"; // always runs
&& and || short-circuit
if (i < n && a[i] > 0) { ... }
// a[i] is never read when i >= n
The ternary operator
int mx = (a > b) ? a : b;
// condition ? value_if_true : value_if_false
SC 428 · Lecture 2 · Decisions · Compile with -Wall to get warnings for the first two
Decisions
switch compares one value against many constants
double a, b;
char op;
cin >> a >> op >> b;
switch (op) {
case '+': cout << a + b; break;
case '-': cout << a - b; break;
case '*': cout << a * b; break;
case '/': cout << a / b; break;
default: cout << "Unknown operator";
}
- The value must be an integer type, a char or an enum. A string or a double does not compile.
- Each case label must be a compile-time constant.
- break leaves the switch. Without it, execution continues into the next case.
- default runs when no case matches. It is optional; put it last.
SC 428 · Lecture 2 · Decisions
Decisions
Fall-through: useful on purpose, a bug by accident
On purpose: several labels, one action
switch (c) {
case 'a': case 'e': case 'i':
case 'o': case 'u':
cout << "vowel";
break;
default:
cout << "consonant";
}
By accident: a missing break
switch (x) {
case 1: cout << "one ";
case 2: cout << "two ";
case 3: cout << "three ";
}
// x = 1 prints: one two three
Use
When
switch
One integer or char value compared with many fixed constants
if / else
Ranges (marks >= 75), several variables, strings or doubles
SC 428 · Lecture 2 · Decisions
Practice P1 · Problem
uses: if / else, switch, %
Even or odd
Task
Read an integer n. It may be negative. Print Even or Odd.
Write the program twice: once with if / else, and once with switch.
Examples
7 -> Odd
-4 -> Even
-7 -> Odd
0 -> Even
Hint: n % 2 is the remainder when n is divided by 2.
SC 428 · Lecture 2 · Practice after Decisions
Practice P1 · Solution
code goes inside main(), with #include <iostream>
Even or odd
With if / else
int n;
cin >> n;
if (n % 2 == 0) {
cout << "Even\n";
} else {
cout << "Odd\n";
}
With switch
int n;
cin >> n;
switch (n % 2) {
case 0:
cout << "Even\n";
break;
default:
cout << "Odd\n";
}
Why test == 0 and not == 1? In C++, -7 % 2 is -1, so n % 2 == 1 would call -7 even.
SC 428 · Lecture 2 · Practice after Decisions
02
Loops
for · while · break and continue · nested loops · patterns
Loops
A for loop has three parts in its header
int sum = 0;
for (int i = 1; i <= n; i++) { // init; condition; update
sum += i;
}
cout << sum; // n = 5 prints 15
1 · init
int i = 1 runs once
2 · check
i <= n false: exit
3 · body
sum += i
4 · update
i++, then back to 2
Use for when you know how many times to repeat. The variable i exists only inside the loop.
SC 428 · Lecture 2 · Loops
Loops
while checks first; do-while runs at least once
while: count the digits of n
int n = 1234, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
// digits == 4
May run zero times. For n = 0 it prints 0 digits: handle that case separately.
do-while: ask until the input is valid
int x;
do {
cout << "Enter x > 0: ";
cin >> x;
} while (x <= 0); // note the ;
The body runs before the first check, so x always gets a value.
SC 428 · Lecture 2 · Loops · Rule of thumb: for when the count is known, while when the data decides
Loops
break leaves the loop; continue skips to the next round
break: first multiple of 7 in [a, b]
for (int i = a; i <= b; i++) {
if (i % 7 == 0) {
cout << i;
break; // stop searching
}
}
continue: print only odd numbers
for (int i = 1; i <= 9; i++) {
if (i % 2 == 0) continue;
cout << i << ' ';
}
// 1 3 5 7 9
break exits only the innermost loop it sits in.
continue in a while loop skips the update below it: easy infinite loop.
SC 428 · Lecture 2 · Loops
Loops
Nested loops: the inner loop runs fully for each outer step
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 4; j++) {
cout << i * j << '\t';
}
cout << '\n'; // end of row i
}
Output
1 2 3 4
2 4 6 8
3 6 9 12
Inner loop
How many times the body runs
j from 1 to m
n × m
j from 1 to i
1 + 2 + … + n = n(n + 1) / 2
SC 428 · Lecture 2 · Loops
Loops · Pattern printing
Ask one question: what does row i contain?
for (int i = 1; i <= n; i++) { // rows
for (int j = 1; j <= i; j++) // i stars
cout << '*';
cout << '\n';
}
- The outer loop walks over the rows.
- Write row i as a formula: here, i stars.
- The inner loop prints that row, then a newline.
n = 4
*
**
***
****
print j instead
1
1 2
1 2 3
1 2 3 4
SC 428 · Lecture 2 · Loops
Loops · Pattern printing
A pyramid is spaces, then stars
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) cout << ' ';
for (int j = 1; j <= 2 * i - 1; j++) cout << '*';
cout << '\n';
}
*
***
*****
*******
Row i (n = 4)
Spaces
Stars
1, 2, 3, 4
3, 2, 1, 0
1, 3, 5, 7
Formula
n − i
2i − 1
Try these
- Inverted triangle: row i has n − i + 1 stars
- Hollow n × n square: star only on the border
- Floyd’s triangle: 1 / 2 3 / 4 5 6
SC 428 · Lecture 2 · Loops
Practice P2 · Problem
uses: for, break, %
Prime check
Task
Read an integer n, where 1 ≤ n ≤ 10^9.
Print Prime if n has no divisors other than 1 and itself. Otherwise print Not prime.
Examples
1 -> Not prime
2 -> Prime
91 -> Not prime
97 -> Prime
Hint: if n = a × b, the smaller factor is at most √n. So you only need to try divisors i with i × i ≤ n.
SC 428 · Lecture 2 · Practice after Loops
Practice P2 · Solution
code goes inside main(), with #include <iostream>
Prime check
int n;
cin >> n;
bool isPrime = (n >= 2); // 0 and 1 are not prime
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << "Prime\n";
} else {
cout << "Not prime\n";
}
How it works
- Assume n is prime, unless it is 0 or 1.
- Try each i from 2 while i × i ≤ n.
- If i divides n, n is not prime; break stops the search.
How fast?
For n = 10^9 the loop runs about 31,623 times instead of 10^9. That is O(√n), explained in the next section.
SC 428 · Lecture 2 · Practice after Loops
03
Big-O intuition
growth rates · counting loops · fast I/O
Big-O
Big-O describes how the work grows with n
≈ 10^8
simple operations per second
A rough budget for a 1-second time limit. Compare it with your algorithm’s step count at the largest n.
1 · Drop constant factors
3n + 5 → O(n)
2 · Keep the fastest-growing term
n² + 100n → O(n²)
3 · Assume the worst case
Searching for a missing value checks all n items
4 · Let the limits choose
n ≤ 10^5 means (10^5)² = 10^10 steps: O(n²) is too slow
SC 428 · Lecture 2 · Big-O
Big-O
Common growth rates, slowest-growing first
Growth
Typical code
Largest n in ~1 s
O(1)
a[i], the formula n(n + 1) / 2
any
O(log n)
halving loop, binary search
10^18
O(√n)
prime check (P2)
10^14
O(n)
one pass: sum, max, count
10^7 to 10^8
O(n log n)
sorting
about 10^6
O(n²)
all pairs (i, j)
about 10^4
O(2^n)
all subsets
about 25
SC 428 · Lecture 2 · Big-O · Limits are rough, from the 10^8 rule of thumb
Big-O
Count how often the innermost line runs
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
work();
n × n → O(n²)
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
work();
n + (n − 1) + … + 1 = n(n + 1) / 2 → O(n²)
for (int i = n; i > 0; i /= 2)
work();
n, n/2, n/4, … 1: about log₂ n steps → O(log n)
for (int i = 0; i < n; i++) work();
for (int j = 0; j < m; j++) work();
One after the other: add → O(n + m)
SC 428 · Lecture 2 · Big-O · Nested loops multiply, sequential loops add
Big-O · Fast I/O
Two lines that speed up large input and output
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int sum = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
sum += x;
}
cout << sum << "\n";
return 0;
}
sync_with_stdio(false)
cin and cout stop syncing with C’s scanf and printf. Do not mix the two styles afterwards.
cin.tie(nullptr)
cin no longer flushes cout before every read.
"\n" instead of endl
endl also flushes. One flush per line is slow for 10^5+ lines.
SC 428 · Lecture 2 · Big-O · Matters only when input or output runs to about 10^5 lines or more
Practice P3 · Problem
uses: Big-O, counting loops
What is the time complexity of each snippet?
E1
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
count++;
E2
for (int i = 1; i < n; i *= 2)
count++;
E3
for (int i = 0; i < n; i++)
for (int j = 0; j < 5; j++)
count++;
E4
for (int i = 0; i < n; i++)
count++;
for (int j = 0; j < n; j++)
count++;
E5
for (int i = 1; i * i <= n; i++)
count++;
E6
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
count++;
Write each answer as O(…) with a one-line reason.
SC 428 · Lecture 2 · Practice after Big-O · Answers on the next slide
Practice P3 · Solution
What is the time complexity of each snippet?
#
Answer
Reason
E1
O(n²)
the inner loop runs 0 + 1 + … + (n − 1) = n(n − 1) / 2 times
E2
O(log n)
i doubles: 1, 2, 4, 8, … and passes n after about log₂ n steps
E3
O(n)
the inner loop always runs 5 times: 5n steps, and constants are dropped
E4
O(n)
two loops one after the other add up: n + n = 2n
E5
O(√n)
the loop stops once i × i passes n, as in the prime check (P2)
E6
O(n³)
three nested loops of n steps each multiply: n × n × n
SC 428 · Lecture 2 · Practice after Big-O · Nested loops multiply, loops in sequence add
04
Arrays
1D and 2D · indexing · out-of-bounds · limitations
Arrays
An array is n boxes side by side in memory
10
a[0]
20
a[1]
30
a[2]
40
a[3]
50
a[4]
Address of a[i] = start + i × sizeof(int). The computer jumps straight there, so a[i] is O(1).
int a[5]; // local: garbage values
int b[5] = {1, 2}; // {1, 2, 0, 0, 0}
int c[5] = {}; // all zeros
int d[] = {4, 8, 15}; // size 3, deduced
a[0] = 7; // first element
a[4] = 9; // last: index n - 1
- Indices run from 0 to n − 1.
- All elements have the same type.
- Global arrays start as zeros; local arrays hold garbage until you set them.
SC 428 · Lecture 2 · Arrays
Arrays
Reading and walking through an array
const int MAXN = 100;
int a[MAXN];
int n;
cin >> n; // assume n <= MAXN
for (int i = 0; i < n; i++) cin >> a[i];
long long sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
int d[] = {4, 8, 15};
for (int x : d) cout << x << ' '; // 4 8 15
int len = sizeof(d) / sizeof(d[0]); // 3
Declare the array for the largest allowed n, then use only the first n slots.
Range-for visits every slot. On a it visits all 100, not just n.
The sizeof trick works only where the array is declared, not inside a function that receives it.
SC 428 · Lecture 2 · Arrays
Arrays
2D arrays: g[row][column]
int g[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++)
cout << g[r][c] << ' ';
cout << '\n';
}
cout << g[1][2]; // 7
1
2
3
4
5
6
7
8
9
10
11
12
Highlighted: g[1][2] = 7, row 1, column 2.
Memory stores row 0, then row 1, then row 2, so g[r][c] is element r × 4 + c. Loop over rows outside and columns inside.
SC 428 · Lecture 2 · Arrays
Arrays · Out of bounds
Touching an index outside 0 … n − 1 is undefined behaviour
int a[5];
a[5] = 42; // compiles, no check
cout << a[-1]; // also undefined
C++ does not check indices. The program may crash, print garbage, quietly overwrite another variable, or pass on your laptop and fail on the judge.
Defences: loop with i < n, not i <= n · v.at(i) on vectors throws an error · test with g++ -fsanitize=address
Arrays
Five limits of plain arrays
Limit
What it means
With vector
Fixed size
The size must be a compile-time constant. int a[n] with n read at runtime is a compiler extension, not standard C++.
Grows at runtime
No length
The array does not know its size; you carry n around yourself.
v.size()
Decays to a pointer
Passed to a function it becomes int*, and the size is lost.
Pass vector<int>&
No copy or assign
b = a; does not compile, and a function cannot return an array.
v2 = v; works
Stack limit
A huge local array such as int a[10000000] inside main can crash. Make it global.
Elements live on the heap
SC 428 · Lecture 2 · Arrays
Practice P4 · Problem
uses: arrays, loops
Array maximum and reversal
Task
Read n (1 ≤ n ≤ 100), then n integers into an array.
- Print the largest value and the index where it first appears.
- Reverse the array in place, without a second array, and print it.
Example
Input:
5
3 9 2 9 1
Output:
9 1
1 9 2 9 3
Hint: element i and element n − 1 − i are mirror images of each other.
SC 428 · Lecture 2 · Practice after Arrays
Practice P4 · Solution
code goes inside main(), with #include <iostream>
Array maximum and reversal
Part 1 · read and find the maximum
int n;
cin >> n;
int a[100];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int maxValue = a[0];
int maxIndex = 0;
for (int i = 1; i < n; i++) {
if (a[i] > maxValue) {
maxValue = a[i];
maxIndex = i;
}
}
cout << maxValue << " " << maxIndex << "\n";
Part 2 · reverse in place
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - 1 - i];
a[n - 1 - i] = temp;
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
Why n / 2? Each swap fixes two elements. Going to n would swap everything back.
SC 428 · Lecture 2 · Practice after Arrays · Both parts are O(n)
Practice P5 · Problem
uses: arrays, loops, index bounds
Is the array sorted?
Task
Read n (1 ≤ n ≤ 100), then n integers into an array.
Print YES if every element is less than or equal to the one after it. Otherwise print NO.
Examples
1 3 3 7 -> YES
2 5 4 -> NO
8 -> YES
Hint: compare each element with its right neighbour, a[i] with a[i + 1]. Think about where the loop must stop.
SC 428 · Lecture 2 · Practice after Arrays
Practice P5 · Solution
code goes inside main(), with #include <iostream>
Is the array sorted?
Part 1 · read the array
int n;
cin >> n;
int a[100];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
Why i < n - 1? The loop reads a[i + 1]. If i reached n − 1, that would be a[n]: out of bounds.
Part 2 · compare neighbours
bool isSorted = true;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
isSorted = false;
}
}
if (isSorted) {
cout << "YES\n";
} else {
cout << "NO\n";
}
SC 428 · Lecture 2 · Practice after Arrays · O(n) time
Practice P6 · Problem
uses: 2D arrays, nested loops
Row and column sums
Task
Read rows and cols (both at most 10), then a grid of integers with that many rows and columns.
On the first line, print the sum of each row. On the second line, print the sum of each column.
Example
Input:
2 3
1 2 3
4 5 6
Output:
6 15
5 7 9
Hint: for column sums, put the column loop outside and the row loop inside.
SC 428 · Lecture 2 · Practice after Arrays
Practice P6 · Solution
code goes inside main(), with #include <iostream>
Row and column sums
Part 1 · read, then row sums
int rows, cols;
cin >> rows >> cols;
int g[10][10];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
cin >> g[r][c];
}
}
for (int r = 0; r < rows; r++) {
int rowSum = 0;
for (int c = 0; c < cols; c++) {
rowSum += g[r][c];
}
cout << rowSum << " ";
}
Part 2 · column sums
cout << "\n";
for (int c = 0; c < cols; c++) {
int colSum = 0;
for (int r = 0; r < rows; r++) {
colSum += g[r][c];
}
cout << colSum << " ";
}
Same loops, swapped. c outside picks a column; r inside walks down it.
SC 428 · Lecture 2 · Practice after Arrays · O(rows × cols) time
05
Vectors
operations · costs · amortized O(1) · 2D vectors · references · pairs
Vectors
A vector is an array that can grow
#include <vector>
vector<int> a; // empty
vector<int> b(5); // {0, 0, 0, 0, 0}
vector<int> c(3, -1); // {-1, -1, -1}
vector<int> d = {3, 1, 4}; // from a list
cout << d.size(); // 3
cout << d[0] << d.back(); // prints 34
Same contiguous memory and O(1) indexing as an array
Knows its own size: v.size()
Grows and shrinks while the program runs
Copies, assigns and returns like an ordinary variable
SC 428 · Lecture 2 · Vectors
Vectors
push_back, pop_back, size, clear
Statement
v afterwards
size()
vector<int> v;
{}
0
v.push_back(4);
{4}
1
v.push_back(7);
{4, 7}
2
v.push_back(1);
{4, 7, 1}
3
v.pop_back();
{4, 7}
2
int x = v.back();
x is 7
2
v.clear();
{}
0
Empty vector
pop_back() or back() on an empty vector is undefined. Check !v.empty() first.
size() is unsigned
When v is empty, v.size() - 1 is a huge number, not -1. Write (int)v.size() - 1.
SC 428 · Lecture 2 · Vectors · front() and back() read the first and last element
Vectors
insert and erase work at a position
vector<int> v = {10, 20, 30, 40};
v.insert(v.begin() + 1, 15); // {10, 15, 20, 30, 40}
v.erase(v.begin() + 3); // {10, 15, 20, 40}
v.erase(v.begin(), v.begin() + 2); // {20, 40}
v.insert(v.end(), 99); // {20, 40, 99}
10
15
20
30
40
After insert(v.begin() + 1, 15): the new 15 (orange) went in, and 20, 30, 40 (blue) each moved one place right.
- v.begin() + i is the position of index i.
- erase(first, last) removes [first, last): last stays.
- Everything after the position shifts: O(n).
SC 428 · Lecture 2 · Vectors
Vectors
resize changes the size; reserve only the capacity
vector<int> v = {1, 2, 3};
v.resize(5); // {1, 2, 3, 0, 0}
v.resize(2); // {1, 2}
v.resize(4, 9); // {1, 2, 9, 9}
v.reserve(100); // size 4, capacity >= 100
v.clear(); // size 0, capacity unchanged
size vs capacity
size = elements in use. capacity = slots already allocated. Always size ≤ capacity.
Which one?
resize(n) before writing v[i]. reserve(n) before n push_backs.
Bug
v.reserve(n); v[0] = 5; is undefined: size is still 0.
SC 428 · Lecture 2 · Vectors
Vectors
2D vectors: a vector of rows
int n, m;
cin >> n >> m;
vector<vector<int>> g(n, vector<int>(m, 0));
for (int r = 0; r < n; r++)
for (int c = 0; c < m; c++)
cin >> g[r][c];
cout << g.size() << ' ' << g[0].size(); // n m
// jagged: row i has i + 1 entries
vector<vector<int>> tri(n);
for (int i = 0; i < n; i++)
tri[i].resize(i + 1);
- Each row is its own vector, so rows may have different lengths.
- g.size() is the number of rows; g[r].size() is the length of row r.
- Unlike int g[n][m], n and m can come from the input.
- Index exactly like a 2D array: g[r][c].
SC 428 · Lecture 2 · Vectors
Vectors
Pass vectors by reference
void byValue(vector<int> v) { // a copy: O(n)
v[0] = 99; // caller unchanged
}
void byRef(vector<int>& v) { // the caller’s vector
v[0] = 99; // caller sees 99
}
long long total(const vector<int>& v) { // no copy, read-only
long long s = 0;
for (int x : v) s += x;
return s;
}
Parameter
Use when
const vector<int>&
you only read it
vector<int>&
the function must change it
vector<int>
you need a private copy
Calling byValue n times on a vector of size n copies n × n elements: an O(n²) cost hidden in one missing &.
SC 428 · Lecture 2 · Vectors
Vectors · Big-O
What each vector operation costs
Operation
Cost
Why
v[i], v.back(), v.size()
O(1)
address arithmetic; size is stored
push_back
amortized O(1)
occasional regrowth, next slide
pop_back
O(1)
size goes down by one
insert / erase at index i
O(n − i)
everything after i shifts
insert / erase at the front
O(n)
every element shifts
search for a value
O(n)
checks elements one by one
clear
O(n)
destroys each element
copy, or pass by value
O(n)
copies every element
SC 428 · Lecture 2 · Vectors · Work at the back is cheap; work at the front or middle is linear
Vectors · Big-O
Why push_back is amortized O(1)
Push number
Capacity
Copies
1
0 → 1
0
2
1 → 2
1
3
2 → 4
2
4
4
0
5
4 → 8
4
6 to 8
8
0
9
8 → 16
8
10 to 16
16
0
When the vector is full, it allocates a bigger block (here 2×), copies everything over, then appends.
1 + 2 + 4 + … < 2n
16 pushes cost 1 + 2 + 4 + 8 = 15 copies. n pushes cost under 3n steps in total: O(1) each on average.
One push can still cost O(n). If you know the final size, reserve(n) avoids every regrowth.
SC 428 · Lecture 2 · Vectors · The growth factor is up to the library: GCC doubles, MSVC grows by 1.5×
Vectors · Pairs
pair keeps two values together
#include <utility>
pair<int, int> p = {3, 7};
cout << p.first << ' ' << p.second; // 3 7
pair<string, int> s = {"Asha", 91};
vector<pair<int, int>> pts;
pts.push_back({2, 5});
pts.push_back({1, 9});
pts.push_back({2, 1});
sort(pts.begin(), pts.end());
// {1, 9} {2, 1} {2, 5}
- The two parts are .first and .second, of any types.
- Pairs compare by first, then by second, so sort orders them that way.
- Common use: keep a value with its index, as pair (value, index).
SC 428 · Lecture 2 · Vectors · sort is in <algorithm>
Practice P7 · Problem
uses: vectors, push_back
Remove the even numbers
Task
Read n, then n integers into a vector.
Print the numbers that are left after removing every even number, in their original order.
Examples
5
2 4 5 6 7 -> 5 7
3
-3 8 1 -> -3 1
Hint: instead of erasing, collect the numbers you keep in a second vector.
SC 428 · Lecture 2 · Practice after Vectors
Practice P7 · Solution
code goes inside main(), with #include <iostream> and <vector>
Remove the even numbers
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
vector<int> odds;
for (int i = 0; i < n; i++) {
if (numbers[i] % 2 != 0) {
odds.push_back(numbers[i]);
}
}
for (int i = 0; i < odds.size(); i++) {
cout << odds[i] << " ";
}
How it works
- vector<int> numbers(n) makes room for n values.
- Each odd number is added to the end of odds.
- % 2 != 0 also catches negative odd numbers.
Why not erase in the loop?
After erasing numbers[i], the next number slides into index i and the loop skips it.
SC 428 · Lecture 2 · Practice after Vectors · One pass: O(n)
Practice P8 · Problem
uses: vector of pairs, functions
Closest point to the origin
Task
Read n, then n points as x y, with coordinates between -1000 and 1000. Store them in a vector<pair<int, int>>.
Print the point closest to (0, 0). If there is a tie, print the first one.
Example
Input:
3
3 4
-1 1
0 5
Output:
-1 1
Hint: distance² = x² + y². Comparing squared distances gives the same answer without sqrt.
SC 428 · Lecture 2 · Practice after Vectors
Practice P8 · Solution
needs #include <iostream>, <vector> and <utility>
Closest point to the origin
Above main()
int squaredDist(pair<int, int> p) {
int x = p.first;
int y = p.second;
return x * x + y * y;
}
The helper keeps main short: it turns a point into one number to compare.
Inside main()
int n;
cin >> n;
vector<pair<int, int>> points(n);
for (int i = 0; i < n; i++) {
cin >> points[i].first >> points[i].second;
}
int best = 0; // index of the closest point so far
for (int i = 1; i < n; i++) {
if (squaredDist(points[i]) < squaredDist(points[best])) {
best = i;
}
}
cout << points[best].first << " "
<< points[best].second << "\n";
SC 428 · Lecture 2 · Practice after Vectors · Using < (not <=) keeps the first point on a tie
Practice P9 · Problem
uses: push_back, size, back, pop_back, empty
Read until zero, print in reverse
Task
Read integers until 0 is entered. The 0 is not part of the list, and you do not know the count in advance.
Print how many numbers were read, then print them in reverse order, removing each one from the vector as you print it.
Example
Input:
4 8 15 16 0
Output:
4
16 15 8 4
Hint: back() reads the last element, pop_back() removes it, and empty() tells you when to stop.
SC 428 · Lecture 2 · Practice after Vectors
Practice P9 · Solution
code goes inside main(), with #include <iostream> and <vector>
Read until zero, print in reverse
vector<int> numbers;
int x;
cin >> x;
while (x != 0) {
numbers.push_back(x);
cin >> x;
}
cout << numbers.size() << "\n";
while (!numbers.empty()) {
cout << numbers.back() << " ";
numbers.pop_back();
}
How it works
- push_back adds each number to the end, so size() is the count.
- back() is the last number read. pop_back() removes it, so the next back() is the one before.
- The loop stops when empty() becomes true.
Last in, first out: this is how a stack works.
SC 428 · Lecture 2 · Practice after Vectors · Every operation used is O(1), so the whole program is O(n)
06
Useful STL functions
reverse · min_element / max_element · accumulate · count · find · swap
STL
Algorithms take a range [first, last)
4
v.begin()
9
.
2
.
7
.
–
v.end()
end() points one past the last element. For an array a of n elements the range is a, a + n.
Call
Header
Gives back
Cost
reverse(first, last)
<algorithm>
nothing; reverses in place
O(n)
min_element, max_element
<algorithm>
iterator to the first min / max
O(n)
accumulate(first, last, init)
<numeric>
init + sum of the range
O(n)
count(first, last, x)
<algorithm>
how many equal x
O(n)
find(first, last, x)
<algorithm>
iterator to first x, or last
O(n)
swap(a, b)
<utility>
nothing; exchanges a and b
O(1)
SC 428 · Lecture 2 · STL
STL
reverse and swap
vector<int> v = {1, 2, 3, 4, 5};
reverse(v.begin(), v.end()); // {5, 4, 3, 2, 1}
reverse(v.begin(), v.begin() + 3); // {3, 4, 5, 2, 1}
int a[] = {7, 8, 9};
reverse(a, a + 3); // {9, 8, 7}
int x = 1, y = 2;
swap(x, y); // x = 2, y = 1
swap(v[0], v[4]); // {1, 4, 5, 2, 3}
- reverse works on any part of a range: the first 3 here.
- Works the same on vectors and arrays.
- swap replaces the three-line temp-variable swap from P4.
SC 428 · Lecture 2 · STL
STL
min_element and max_element
vector<int> v = {4, 9, 2, 9, 7};
int biggest = *max_element(v.begin(), v.end()); // 9
int smallest = *min_element(v.begin(), v.end()); // 2
// the index of the first largest value
int pos = max_element(v.begin(), v.end()) - v.begin();
cout << pos; // 1
int a[] = {5, -3, 8};
int largest = *max_element(a, a + 3); // 8
They return a position
The * in front reads the value stored there. Subtracting v.begin() gives the index.
Empty vector
There is no largest value. Check that the vector is not empty first.
SC 428 · Lecture 2 · STL · For just two values, use min(a, b) and max(a, b)
STL
accumulate, count and find
vector<int> v = {5, 3, 5, 1};
int total = accumulate(v.begin(), v.end(), 0); // 14
int fives = count(v.begin(), v.end(), 5); // 2
int a[] = {2, 7, 2, 2};
int twos = count(a, a + 4, 2); // 3
if (find(v.begin(), v.end(), 3) != v.end()) {
cout << "3 is in v\n";
}
int pos = find(v.begin(), v.end(), 3) - v.begin();
cout << pos; // 1
accumulate
The last argument is the starting value. It is in <numeric>.
count
Works on vectors and arrays alike.
find
Returns v.end() when the value is not there. Check before using the result.
SC 428 · Lecture 2 · STL · All three are O(n)
Practice P10 · Problem
uses: STL functions
Redo earlier work with the STL
Task
Given a vector<int> v and an integer x, use one STL function for each:
- The largest value in v (as in P4)
- Reverse v in place (as in P4)
- How many times x appears in v
- The sum of all values in v
Example
v = {4, 9, 2, 9}
x = 9
1. 9
2. {9, 2, 9, 4}
3. 2
4. 24
Hint: max_element, reverse, count, accumulate.
SC 428 · Lecture 2 · Practice after STL
Practice P10 · Solution
inside main(), with <vector>, <algorithm> and <numeric>
Redo earlier work with the STL
// 1. largest value
int biggest = *max_element(v.begin(), v.end());
// 2. reverse in place
reverse(v.begin(), v.end());
// 3. how many times x appears
int times = count(v.begin(), v.end(), x);
// 4. sum of all values
int total = accumulate(v.begin(), v.end(), 0);
Compare
- Same O(n) as the loops you wrote in P4.
- Fewer lines, so fewer places for index mistakes.
- Write the loop once yourself first, so you know what each function does.
SC 428 · Lecture 2 · Practice after STL
Recap
Six things to remember from today
Decisions
Order else-if tests from strictest to loosest. Every switch case needs a break.
Loops
For patterns, ask what row i contains. Nested loops multiply the work.
Big-O
About 10^8 simple steps per second. Let the input size choose the algorithm.
Arrays
Valid indices are 0 to n − 1. Anything outside is undefined behaviour.
Vectors
push_back is cheap; insert and erase in the middle are O(n). Pass by reference.
STL
Ranges run from begin() up to, not including, end().