Introduction
Getting Started · C++ 1
What C++ Is
C++ is a compiled, statically typed language. You write source code in a .cpp file, the compiler translates it straight into machine code for your computer, and the result is a fast standalone program. Types are fixed when you declare a variable, and the compiler checks them before anything runs.
- A compiler:
g++(Linux, or MinGW on Windows),clang++(comes with Xcode on Mac), or Microsoft Visual C++. - An editor or IDE: VS Code with the C/C++ extension, CLion, Visual Studio, or Code::Blocks. An IDE compiles with one key and underlines mistakes as you type.
- Source code — what you type, in
.cppand.hfiles - Compiler — turns source into an executable; reports syntax errors
- Executable — the finished program (
a.out,hello.exe)
Your First Program
hello.cpp
#include <iostream>
using namespace std;
int main()
{
// Display a greeting in the console window
cout << "Hello, World!" << endl;
return 0;
}Compile and run from a terminal
g++ -std=c++17 -Wall hello.cpp -o hello
./helloHello, World!Read it line by line
#include <iostream>brings in the input/output library. Every program lists the headers it uses.using namespace std;lets you writecoutinstead ofstd::cout. Fine in a course; many professionals writestd::instead.int main()is where the program starts. Every program has exactly one.cout << ... << endlsends text to the screen;endlends the line. Each statement ends with a semicolon.return 0;tells the operating system the program finished normally.
-Wall turns on the compiler’s warnings. Read them: a warning is usually a bug the compiler was not quite sure about.
Comments and Style
Comments
// One line, to the end of the line
/* Several lines,
between the markers */
/**
A documentation comment above a function:
@param x what the parameter means
@return what comes back
*/Conventions
- Variables and functions in snake_case or lowerCamelCase:
total_score,printBalance. Pick one style and keep it. - Classes in UpperCamelCase:
BankAccount - Constants in ALL_CAPS:
const int MAX_SIZE = 100; - One statement per line, indent the body of every brace pair, and use blank lines between functions.
Three Kinds of Errors
| Kind | When it shows up | Example |
|---|---|---|
| Compile-time (syntax) error | When you compile; no executable is produced until it is fixed | A missing semicolon, Cout with a capital C, a variable used before it is declared |
| Run-time error | While the program runs; it may crash, or worse, quietly misbehave | Dividing an integer by zero, reading past the end of an array (undefined behavior: no error message is guaranteed) |
| Logic error | Never announced; the program runs and gives the wrong answer | Integer division where you wanted a decimal, an off-by-one in a loop |
C++ is case sensitive and does not check array bounds. cout and Cout are different names; and values[10] on a ten-element array compiles and runs, reading whatever memory is there. Checking bounds is your job (or use vector::at).
What the messages look like
average.cpp, line 6 missing its semicolon
average.cpp: In function 'int main()':
average.cpp:6:34: error: expected ';' before 'return'
6 | cout << total / count << endl
| ^
| ;
7 | return 0;
| ~~~~~~The same program, fixed, run with count still 0
Floating point exception- 1. A compiler message is
file:line:column: error:followed by what the compiler expected, then the line with a caret under the spot. Here the missing semicolon is on line 6 but the compiler only notices atreturnon line 7, so look at the line before the one it names too. Fix the first error and recompile; the rest are usually echoes. - 2. A
warning:still produces a program, but read it:control reaches end of non-void function,'x' is used uninitializedandsuggest parentheses around assignment used as truth valueare real bugs. Always compile with-Wall. - 3. A run-time crash says little:
Floating point exceptionfor integer division by zero,Segmentation faultfor a bad memory access or runaway recursion. Compile with-g -fsanitize=addresswhile learning and the report names the line.
Programming with Numbers and Strings
Getting Started · C++ 1
Variables and Types
A variable has a type, a name and a value. Declare the type before the name; the type never changes. Always initialize: an uninitialized local variable holds garbage, not zero.
int cans_per_pack = 6; // whole number
double can_volume = 0.335; // number with a fractional part
bool done = false; // true or false
char grade = 'A'; // a single character, in single quotes
string name = "Harry"; // text: #include <string>
const int MAX_SIZE = 100; // a constant: cannot be changed later
int count; // DANGER: uninitialized, holds garbage| Type | Holds | Range or notes |
|---|---|---|
int | Whole numbers | Usually about ±2.1 billion; overflow wraps or misbehaves silently |
long long | Big whole numbers | About ±9 × 1018 |
double | Decimal numbers | About 15 significant digits; 0.1 + 0.2 is not exactly 0.3 |
bool | true or false | Prints as 1 or 0 unless you use boolalpha |
char | One character | Single quotes: 'a'; really a small integer (its code) |
string | Text | A class from <string>; grows as needed; compare with == |
unsigned, size_t | Non-negative whole numbers | What .size() returns; mixing with int in comparisons draws a warning for good reason |
Arithmetic
| Operator | Meaning | Example |
|---|---|---|
+ - * | Add, subtract, multiply | 7 * 3 → 21 |
/ | Division. Integer ÷ integer drops the fraction | 7 / 3 → 2, but 7.0 / 3 → 2.333… |
% | Remainder (modulus), integers only | 7 % 3 → 1; n % 2 == 0 tests for even |
++ -- | Add or subtract 1 | count++; is count = count + 1; |
+= -= *= /= | Combine and assign | total += price; |
Casts and the math library
#include <cmath>
#include <cstdlib>
double price = 19.99;
int dollars = price; // 19: assigning a double to an int truncates (with a warning)
int dollars2 = static_cast<int>(price); // 19, and says so on purpose
int rounded = static_cast<int>(price + 0.5); // 20; or round(price) from <cmath>
double r = sqrt(2.0); // 1.41421...
double p = pow(2.0, 10); // 1024
double a = fabs(-4.5); // 4.5 (abs is for integers)
int big = max(3, 9); // 9, from <algorithm>
int dice = rand() % 6 + 1; // 1 to 6; call srand(time(0)) once firstThe classic mistake: double average = sum / count; with two int variables divides first, as integers. Fix it with a cast: static_cast<double>(sum) / count, or make one of them a double.
Strings
#include <string>
string greeting = "Hello";
int n = greeting.length(); // 5 (also .size())
char first = greeting[0]; // 'H' (positions start at 0; no bounds check)
char safe = greeting.at(0); // same, but throws if out of range
string sub = greeting.substr(1, 2); // "el" (start position, LENGTH)
int where = greeting.find("l"); // 2, or string::npos if not found
string both = greeting + ", World"; // concatenation
greeting += "!"; // append
bool same = greeting == "Hello!"; // == compares the letters
string mixed = "Total: " + to_string(7); // numbers must be converted first
int value = stoi("42"); // string to int; stod for doubleCharacters
#include <cctype>
char c = 'a';
isdigit(c), isalpha(c), isspace(c) // tests
toupper(c) // 'A' (returns an int; cast back to char)
c - '0' // the digit value of a digit character
for (char ch : greeting) { cout << ch << endl; } // visit every characterEscape sequences
| Write | Get |
|---|---|
\" | a double quote inside a string |
\\ | one backslash |
\n | a new line (endl also flushes the output) |
\t | a tab |
Input and Formatted Output
volume.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Please enter the number of bottles: ";
int bottles;
cin >> bottles;
cout << "Price per bottle: ";
double price;
cin >> price;
double total = bottles * price;
cout << fixed << setprecision(2);
cout << "Total: $" << total << " for " << bottles << " bottles" << endl;
return 0;
}Manipulator (<iomanip>) | Meaning | Note |
|---|---|---|
fixed << setprecision(2) | Decimals with exactly 2 places | Set once; stays on for the rest of the program |
setw(8) | Right-align the next value in 8 columns | Applies to the next item only; repeat it for each column |
left, right | Alignment inside setw | |
boolalpha | Print true/false instead of 1/0 |
Reading a whole line
string name;
getline(cin, name); // keeps the spaces
// After cin >> number, the newline is still waiting:
cin >> age;
cin.ignore(1000, '\n'); // throw away the rest of that line
getline(cin, address); // now this worksDetecting the end of input
double value;
while (cin >> value) // false at end of file or on a non-number
{
total += value;
count++;
}
// Ctrl+D (Mac, Linux) or Ctrl+Z (Windows) ends keyboard inputDecisions
Control Flow · C++ 1
The if Statement
if (floor > 13)
{
actual_floor = floor - 1;
}
else if (floor == 13)
{
cout << "There is no 13th floor." << endl;
}
else
{
actual_floor = floor;
}| C++ | Math | Note |
|---|---|---|
> >= | > ≥ | |
< <= | < ≤ | |
== | = | Two equals signs. if (x = 5) compiles and is always true: it assigns 5. |
!= | ≠ |
| Operator | True when |
|---|---|
a && b | both are true (and) |
a || b | at least one is true (or) |
!a | a is false (not) |
&& and || short-circuit: in x != 0 && 1 / x > 2 the division is skipped when x is 0, so it is safe.
Comparing Strings and Decimals
if (word == "quit") // strings compare by content in C++
if (word < other) // alphabetical (uppercase sorts before lowercase)
if (word.find("a") != string::npos) // contains
const double EPSILON = 1E-12;
if (fabs(x - y) < EPSILON) // decimals: compare with a tolerance
if (count) // any non-zero number counts as trueDo not compare C-style strings with ==. A string literal or char array compared to another with == compares addresses. Use string variables and the comparison is by content.
The switch Statement and the Conditional Operator
switch
switch (digit)
{
case 1:
name = "one";
break;
case 2:
name = "two";
break;
default:
name = "many";
break;
}
// works on integers and characters, not strings or doublesThe ? : operator
int larger = (a > b) ? a : b;
string label = (n % 2 == 0) ? "even" : "odd";
// condition ? value_if_true : value_if_falseIn a switch a missing break falls through into the next case. It is occasionally useful (case 1: case 2: share one body) and usually a bug.
Mistakes to Watch For
if (x = 5)assigns and is always true; with-Wallthe compiler sayswarning: suggest parentheses around assignment used as truth value. Some people writeif (5 == x)so the typo will not compile.- A semicolon right after the condition,
if (x > 0);, ends the if. The block below always runs. - Dangling else: an
elsebelongs to the nearestif. Use braces every time and this cannot bite you. - Testing
0 < x < 10compiles but means(0 < x) < 10, which is always true;-Wallsayswarning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning. Write0 < x && x < 10. switchon astring:error: switch quantity not an integer. Use anif/else ifchain for strings and doubles.- Comparing a
char*or literal with==:warning: comparison with string literal results in unspecified behavior. Put the text in astringfirst:string(argv[1]) == "quit". - Ranges: order the tests so each one only has to check one boundary, from largest down or smallest up.
// Letter grade: each test assumes the earlier ones failed
if (score >= 90) { grade = "A"; }
else if (score >= 80) { grade = "B"; }
else if (score >= 70) { grade = "C"; }
else { grade = "F"; }Loops
Control Flow · C++ 1
The Three Loops
| Loop | Use it when | Shape |
|---|---|---|
while | You do not know how many times; stop when a condition changes | while (balance < TARGET) { ... } |
for | You count: a known number of times, or over the positions of an array, vector or string | for (int i = 0; i < 10; i++) { ... } |
do | The body must run at least once, such as asking for input until it is valid | do { ... } while (value <= 0); |
// while: years until the balance doubles
int year = 0;
while (balance < 2 * initial) // tested before every turn
{
year++;
balance = balance + balance * RATE / 100; // moves toward the exit
}
// for: the count is known
for (int i = 1; i <= 10; i++)
{
cout << i << " squared is " << i * i << endl;
}
// range-based for: every element, no index
for (double v : values)
{
total += v;
}
// do: at least once
int value;
do
{
cout << "Enter a positive number: ";
cin >> value;
}
while (value <= 0); // tested AFTER the body1 squared is 1
2 squared is 4
...
10 squared is 100Choosing a loop
- 1. Do you know before the loop starts how many times it runs (a count,
v.size(),s.length())? Usefor. - 2. Do you want every element of a vector, array or string and never its position? Use the range-based
for (double v : values); add&(for (double& v : values)) if the loop must change the elements, otherwise it changes copies. - 3. Otherwise, when the stop depends on something computed as you go (a balance, input, a guess), use
while, and make sure the body changes a variable named in the condition. - 4. Must the body run at least once before the test makes sense (read, then check)? Use
do. Forgetting the semicolon after itswhile (...)giveserror: expected ';' beforewhatever comes next.
Common Loop Algorithms
Sum, average, count
double total = 0;
int count = 0;
double input;
while (cin >> input)
{
total = total + input;
count++;
}
double average = 0;
if (count > 0) { average = total / count; }Maximum and minimum
double largest;
cin >> largest; // start with the first value
double input;
while (cin >> input)
{
if (input > largest)
{
largest = input;
}
}Sentinel value
// Stop at a value that cannot be real data
cout << "Enter salaries, -1 to finish: ";
double salary;
cin >> salary;
while (salary != -1)
{
sum += salary;
cin >> salary;
}Prompting until a flag is set
bool done = false;
while (!done)
{
string input;
cin >> input;
if (input == "Q") { done = true; }
else { process(input); }
}Nested Loops and Loop Control
Nested loops: a table
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 4; col++)
{
cout << setw(4) << row * col;
}
cout << endl; // end the row
} 1 2 3 4
2 4 6 8
3 6 9 12break and continue
for (int i = 0; i < n; i++)
{
if (values[i] < 0) { continue; } // skip this turn
if (values[i] == target) { break; } // leave the loop
total += values[i];
}Both are legal, but many courses ask you to express the exit in the condition instead. break leaves only the innermost loop.
Off-by-One and Other Traps
- Counting from 0 to
n - 1with<, or from 1 tonwith<=. Mixing them runs one time too many or too few. Trace a tiny case (n = 2) by hand. - A loop whose condition never changes is infinite. Make sure the body moves toward the exit.
- Floating-point counters drift:
for (double x = 0; x != 1; x += 0.1)never stops. Count with an integer and compute the double inside. for (int i = 0; i < v.size(); i++)compares a signedintwith an unsignedsize_t; the compiler warns. Usesize_t iorint n = v.size();first.- The variable declared in a
forheader exists only inside that loop. Usingiafter the closing brace giveserror: 'i' was not declared in this scope. for (int i = 0; i <= v.size(); i++)runs one turn too many. Withv[i]nothing is reported and you read garbage; withv.at(i)the program stops withterminate called after throwing an instance of 'std::out_of_range'. Valid positions end atsize() - 1, so the test is<.- A semicolon after the header,
for (int i = 0; i < n; i++);, is an empty loop; the block below runs once withi == n. cin >> valuewhen the user types letters: the read fails silently,valuebecomes 0, and every latercinfails too, sowhile (value <= 0)never ends. Testif (!cin), thencin.clear()and discard the bad input withcin.ignore(1000, '\n').
Functions
Control Flow · C++ 1
Declaring and Calling
A function packages a computation under a name so you can call it from many places and test it alone. The compiler must see the function (or at least its prototype) before the call, so either define functions above main or list prototypes at the top.
cube.cpp
#include <iostream>
using namespace std;
/**
Computes the volume of a cube.
@param side_length the length of one side
@return the volume
*/
double cube_volume(double side_length)
{
double volume = side_length * side_length * side_length;
return volume;
}
int main()
{
double result = cube_volume(2); // the call; 2 is the argument
cout << result << endl; // 8
return 0;
}| Part | In the example | Rules |
|---|---|---|
| Return type | double | The type of the value the function gives back; void for none |
| Name | cube_volume | Usually a verb or what it computes |
| Parameters | double side_length | Variables that receive the arguments, each with its own type |
| Body | between the braces | Must return a value of the declared type on every path, unless void |
| Prototype | double cube_volume(double side_length); | The header alone, with a semicolon, placed above main when the definition comes later. Without it, a call above the definition gives error: 'cube_volume' was not declared in this scope |
Writing a function, step by step
- 1. Say in one sentence what it computes, and name it for that:
cube_volume,is_valid_score,print_report. - 2. The parameters are the values that differ from call to call, each with a type. Anything you can compute from them belongs in the body.
- 3. Pick the return type from what comes back:
doublefor a computed number,boolfor a test,voidwhen the function only prints. Do not mix printing and returning in one function. - 4. Decide how each parameter is passed: by value for numbers,
const&for strings, vectors and objects you only read,&only when the function must change the caller’s variable (next section). - 5. Write the documentation comment, then the body, ending in
return(unlessvoid). Put a prototype abovemainif the definition sits below it. - 6. Test it alone from a small
mainwith inputs whose answers you know:cube_volume(1)is 1,cube_volume(2)is 8.
Value, Reference and const Reference Parameters
This is the part of C++ that other languages hide. A parameter is a copy unless you say otherwise with &.
By value: a copy
void add_interest(double balance, double rate)
{
balance = balance + balance * rate / 100; // changes the copy only
}
// caller:
double savings = 1000;
add_interest(savings, 5);
cout << savings << endl; // still 1000By reference: the caller's variable itself
void add_interest(double& balance, double rate)
{
balance = balance + balance * rate / 100; // changes the caller's variable
}
// caller:
double savings = 1000;
add_interest(savings, 5);
cout << savings << endl; // 1050
void swap_values(int& a, int& b)
{
int temp = a; a = b; b = temp;
}| Parameter | Write | Use when |
|---|---|---|
| Value | double x | Small things (numbers, chars, bools) the function only reads |
| Reference | double& x | The function must change the caller’s variable, or return more than one result |
| Const reference | const string& s, const vector<int>& v | Big things (strings, vectors, objects) the function only reads: no copy is made, and the compiler stops you changing it |
An argument passed by reference must be a variable: add_interest(1000, 5) does not compile (error: cannot bind non-const lvalue reference of type 'double&' to an rvalue of type 'double'), since there is nothing to change. A const& parameter accepts literals too.
Scope, Overloading and Stepwise Refinement
Scope
int main()
{
int sum = 0; // visible in main only
for (int i = 1; i <= 10; i++) // i exists only in this loop
{
sum += square(i);
}
// i is gone here
}
int square(int x) // x and result exist only here
{
int result = x * x;
return result;
}Overloading and default arguments
double area(double radius)
{
return 3.14159 * radius * radius;
}
double area(double width, double height)
{
return width * height;
}
void greet(string name, string greeting = "Hello")
{
cout << greeting << ", " << name << endl;
}
greet("Ann"); // Hello, Ann
greet("Ann", "Hi"); // Hi, AnnStepwise refinement: write main as a list of calls to functions that do not exist yet, each named for one job (read_scores, compute_average, print_report), then write each function. Keep functions short enough to read without scrolling, and give every one a documentation comment.
Mistakes to watch for
- Wrong number of arguments:
cube_volume()giveserror: too few arguments to function 'double cube_volume(double)'. - A non-void function with a path that does not return: only
warning: control reaches end of non-void function, and the caller gets garbage. Treat that warning as an error. - Forgetting
&on a parameter the function must change: it compiles, the copy changes, and the caller sees nothing. The reverse,&on a parameter you only read, is harmless but letconst&say so. - Using a function’s local variable from the caller:
error: 'volume' was not declared in this scope. Locals vanish when the function returns;returnthe value instead. - Declaring without initializing:
int sum; sum += x;compiles withwarning: 'sum' is used uninitializedand starts from whatever was in memory. Writeint sum = 0;. - A
returninside theforloop ends the function on the first turn. Move it after the loop.
Lists: Arrays and Vectors
Data · C++ 1
Arrays
An array holds a fixed number of values of one type, decided when the program is compiled. Positions start at 0. C++ does not check bounds and an array does not know its own length, which is why most C++ courses move to vector quickly.
const int CAPACITY = 10;
double values[CAPACITY]; // ten uninitialized doubles
double zeros[CAPACITY] = {}; // ten zeros
int primes[] = { 2, 3, 5, 7, 11 }; // size 5, filled on creation
values[0] = 32; // first element
values[9] = 3.5; // last element
values[10] = 1; // compiles, runs, corrupts memory: undefined behavior
int n = sizeof(primes) / sizeof(primes[0]); // 5: the only way to askPassing arrays to functions
// An array parameter is really a pointer: the size must travel with it
double sum(const double values[], int size)
{
double total = 0;
for (int i = 0; i < size; i++)
{
total += values[i];
}
return total;
}
// The function can change the caller's array; const promises it will not.Two-dimensional arrays
const int ROWS = 3, COLUMNS = 4;
int board[ROWS][COLUMNS] = {};
board[1][2] = 7;
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLUMNS; c++)
{
cout << setw(4) << board[r][c];
}
cout << endl;
}
// A function parameter must give the column count: int board[][COLUMNS]Vectors: Arrays That Grow
#include <vector>
vector<double> values; // empty
vector<double> ten(10); // ten zeros
vector<int> primes = { 2, 3, 5, 7, 11 };
values.push_back(32); // append
values.push_back(54);
double first = values[0]; // no bounds check
double safe = values.at(0); // throws out_of_range if bad
values[1] = 60; // replace
int n = values.size(); // 2 (a method, with parentheses)
values.pop_back(); // remove the last
bool empty = values.empty();
for (double v : values) { cout << v << endl; }Arrays vs vectors
| Array | vector | |
|---|---|---|
| Size | Fixed at compile time | Grows and shrinks at run time |
| Length | Not stored; pass it along | v.size() |
| Bounds | Never checked | v.at(i) checks; v[i] does not |
| As a parameter | Pointer plus size | const vector<int>& v (no copy) or vector<int>& v to change it |
| Copy | = does not work | vector<int> w = v; makes a real copy |
Common vector algorithms
// maximum
double largest = values[0];
for (size_t i = 1; i < values.size(); i++)
{
if (values[i] > largest) { largest = values[i]; }
}
// linear search
int pos = -1;
for (size_t i = 0; i < values.size() && pos == -1; i++)
{
if (values[i] == target) { pos = i; }
}
// insert and remove in the middle
values.insert(values.begin() + 2, 99); // before position 2
values.erase(values.begin() + 2); // remove position 2
// swap two elements
swap(values[i], values[j]);Useful Library Calls
#include <algorithm>
#include <numeric>
sort(values.begin(), values.end()); // ascending, in place
reverse(values.begin(), values.end());
double total = accumulate(values.begin(), values.end(), 0.0); // sum; 0.0 keeps it a double
auto it = find(values.begin(), values.end(), 42); // iterator, or values.end() if absent
bool has = it != values.end();
int count_big = count_if(values.begin(), values.end(), [](double v) { return v > 50; });
double largest = *max_element(values.begin(), values.end());
vector<vector<int>> table(3, vector<int>(4, 0)); // a 3 by 4 table of zerosv[i] never checks the index. Reading past the end is undefined behavior: it may crash, print garbage, or seem to work until it does not. While learning, use v.at(i) or compile with -fsanitize=address so the error is reported.
Mistakes to watch for
vector<int> v;without#include <vector>:error: 'vector' was not declared in this scope. Every container has its own header.v.at(3)on three elements stops the program withterminate called after throwing an instance of 'std::out_of_range'followed bywhat(): vector::_M_range_check: __n (which is 3) >= this->size() (which is 3). The samev[3]prints nothing and corrupts memory; with-fsanitize=addressyou getERROR: AddressSanitizer: heap-buffer-overflowand the line.sort(v)giveserror: no matching function for call to 'sort(std::vector<int>&)'. Algorithms take a range:sort(v.begin(), v.end()).- Passing a vector by value to a function that fills or sorts it: the function works on a copy and the caller’s vector is unchanged. Take
vector<int>& v. accumulate(..., 0)on avector<double>adds inintand drops every fraction. The third argument sets the type: write0.0.
Files and Exceptions
Data · C++ 1
Reading and Writing Text Files
line_numberer.cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream in("input.txt"); // opens for reading
ofstream out("output.txt"); // creates or overwrites
if (!in) // did the file open?
{
cout << "Cannot open input.txt" << endl;
return 1;
}
string line;
int line_number = 1;
while (getline(in, line))
{
out << "/* " << line_number << " */ " << line << endl;
line_number++;
}
in.close();
out.close(); // also happens automatically at the end of the scope
return 0;
}| Call | Reads |
|---|---|
getline(in, line) | the rest of the current line; false at the end of the file |
in >> word | the next whitespace-separated word into a string |
in >> number | the next number; false if it is not a number or the file ended |
in.get(ch) | one character, spaces and newlines included |
in.fail(), in.eof() | tests after a read: did it fail, and was it because the file ended. Testing eof() before reading runs the loop one extra time |
Reading a file safely, step by step
- 1. Get the name from
argv[1]or the user; it is relative to the working directory. - 2. Open an
ifstreamand test it at once:if (!in). A missing file is not an exception in C++; the stream just fails, and every read after that silently does nothing. - 3. Make the read itself the loop condition:
while (getline(in, line))orwhile (in >> value). It is false exactly when there is nothing more, so the loop never processes a phantom last line. - 4. Convert with
istringstream(orstoi/stodinsidetry) and check it succeeded, so one bad line is reported and skipped instead of poisoning the stream. - 5. Let the stream close itself at the end of the scope, or call
close()when you want the file available sooner.
ifstream in(filename);
if (!in)
{
cout << "Cannot open " << filename << endl;
return 1;
}
string line;
double total = 0;
while (getline(in, line)) // false at the end of the file
{
if (line.empty()) { continue; } // skip blank lines
istringstream parser(line);
double value;
if (parser >> value) // did the conversion work?
{
total += value;
}
else
{
cout << "Skipping bad line: " << line << endl;
}
}
cout << "Total: " << total << endl;Taking a line apart
#include <sstream>
string line = "Smith, Jane, 92";
istringstream parser(line); // read from a string as if it were a file
string last, first;
int score;
getline(parser, last, ','); // up to the comma
getline(parser, first, ',');
parser >> score;Reading numbers
// One or more per line, until the file ends
double value;
double total = 0;
while (in >> value)
{
total += value;
}
// Everything into a vector
vector<double> data;
while (in >> value) { data.push_back(value); }File names are relative to the working directory, which in an IDE is usually the project folder. Command-line arguments arrive in main(int argc, char* argv[]): argv[1] is the first one, as a C string; wrap it in string.
Mistakes to watch for
- No
if (!in)check: a wrong file name produces no message and an empty result, usually a total of 0. The working directory is the usual culprit. while (!in.eof())with the read inside the loop processes the last line twice, becauseeofonly becomes true after a read fails. Put the read in the condition.cin >> nfollowed bygetline(cin, name)gives an emptyname:>>leaves the newline behind. Callcin.ignore(1000, '\n')first, or read every line withgetlineand parse it.- A non-number in the input:
in >> valuefails, leavesvalueas 0, and the stream stays failed untilin.clear(). Everything after the bad token is skipped without a word. ofstream out("input.txt")erases the file you meant to read, before you read a byte. Open output files under a different name.
Exceptions
When something goes wrong at run time, code can throw an exception: an object that describes the problem. If nothing catches it, the program terminates with a message. You can throw your own and catch the ones you can recover from. In C++ exceptions are used for genuinely exceptional situations; ordinary failures such as “file not found” are reported by return values and stream states.
Throwing
#include <stdexcept>
void withdraw(double amount)
{
if (amount > balance)
{
throw invalid_argument("Amount exceeds balance");
}
balance = balance - amount;
}Catching
try
{
int value = stoi(input); // throws invalid_argument if not a number
double x = values.at(value); // throws out_of_range if bad index
account.withdraw(x);
}
catch (invalid_argument& e)
{
cout << "Bad input: " << e.what() << endl;
}
catch (out_of_range& e)
{
cout << "No such position: " << e.what() << endl;
}Standard exception (<stdexcept>) | Thrown by / used for |
|---|---|
invalid_argument | stoi("abc"); your own argument checks |
out_of_range | v.at(i), s.at(i), stoi on a huge number |
runtime_error | Problems detected while running, with a message |
logic_error | Mistakes in the program’s own logic |
exception | The base of all of them: catch (exception& e) catches everything standard |
Custom Exceptions and Good Habits
Your own exception class
class InsufficientFundsError : public runtime_error
{
public:
InsufficientFundsError(const string& message)
: runtime_error(message) {}
};
// throw InsufficientFundsError("Balance is " + to_string(balance));
// catch (InsufficientFundsError& e) { cout << e.what() << endl; }Why catch by reference
catch (exception& e)catches the real object;catch (exception e)copies it and slices off the subclass part, losing the specific message.- Order
catchblocks from most specific to most general; a general one first would swallow the rest. - Throw by value, catch by reference: the rule of thumb in every C++ style guide.
- Throw early: check arguments at the top of a function and throw with a clear message.
- Catch late: catch where you can actually do something, often in
mainor the input loop, not where the problem was found. - Never leave a
catchblock empty. At least printe.what(). - Resources clean themselves up: an
ifstream,stringorvectordeclared in a block is released when the block ends, even when an exception flies through it. This is why C++ has nofinally.
Sets and Dictionaries: set and map
Data · C++ 1
Sets
A set holds values with no duplicates. set keeps them sorted; unordered_set is faster and has no order. Inserting a value that is already there does nothing. Use a set when the question is only “is it in there?”
#include <set>
#include <unordered_set>
set<string> names; // sorted
names.insert("Romeo");
names.insert("Juliet");
names.insert("Romeo"); // ignored: already present
cout << names.size() << endl; // 2
bool there = names.count("Juliet") > 0; // or names.find("Juliet") != names.end()
names.erase("Romeo");
for (const string& name : names) // in sorted order
{
cout << name << endl;
}
unordered_set<int> seen; // no order, fasterset | unordered_set | |
|---|---|---|
| Order when you iterate | Sorted (by <) | Unpredictable |
| Speed of insert / count / erase | Logarithmic | Constant on average |
| Elements must | Be comparable with < | Be hashable (numbers, strings; your own types need a hash function) |
Set algebra lives in <algorithm>: set_union, set_intersection and set_difference take two sorted ranges and write the result into a third container through an inserter such as inserter(result, result.begin()).
Maps (Dictionaries)
A map stores key → value pairs. Each key appears once and looks up its value directly, like a word in a dictionary. map keeps keys sorted; unordered_map is faster and unordered.
#include <map>
map<string, int> scores;
scores["Harry"] = 90; // add or replace
scores["Sally"] = 95;
int s = scores["Harry"]; // 90
int fred = scores["Fred"]; // 0: [] INSERTS a default value for a missing key!
bool has = scores.count("Sally") > 0; // test without inserting
scores.erase("Harry");
auto it = scores.find("Sally"); // iterator to the pair, or scores.end()
if (it != scores.end())
{
cout << it->first << " -> " << it->second << endl; // key and value
}
for (const auto& entry : scores) // every pair, sorted by key
{
cout << entry.first << " -> " << entry.second << endl;
}
for (const auto& [name, score] : scores) // C++17 structured binding
{
cout << name << " -> " << score << endl;
}Counting with a map
// How many times does each word occur?
map<string, int> counts;
string word;
while (in >> word)
{
counts[word]++; // a missing key starts at 0, then becomes 1
}
// the most common word
string best;
int best_count = 0;
for (const auto& [w, c] : counts)
{
if (c > best_count) { best = w; best_count = c; }
}Grouping with a map of vectors
map<char, vector<string>> by_letter;
for (const string& name : names)
{
by_letter[name[0]].push_back(name); // [] creates the empty vector on first use
}
for (const auto& [letter, group] : by_letter)
{
cout << letter << ": " << group.size() << " names" << endl;
}m[key] on a missing key inserts it with a default value (0 or an empty string). That is handy for counting and a trap when testing. To look without touching, use count or find.
Choosing a Container
| You need | Use |
|---|---|
| Values in order, by position, possibly repeated | vector |
| A fixed count of values of one type, fastest possible | an array (or std::array) |
| Membership only, no duplicates | unordered_set (or set for sorted output) |
| Look up a value by a key | unordered_map (or map for sorted keys) |
| First in, first out | queue |
| Last in, first out | stack |
| Insert and remove at both ends | deque |
Deciding, in order
- 1. Will you look values up by a name, id or other key? A
map; rememberm[key]on a missing key silently inserts a default value, so test withcountorfindfirst when you only want to look. - 2. Is the only question “have I seen this before?” A
set. - 3. Does position matter, or can the same value appear twice? A
vector, or an array if the count is fixed from the start. - 4. Do you need the output sorted? Use
set/map; if not, theunordered_versions are faster. Both need#includeof their own header.
A vector works where a set or map belongs, but find on a vector checks every element while set::count is a handful of steps. All of these are templates: you say the element type in angle brackets, vector<double>, map<string, int>, and the compiler builds the right container. Every one has size(), empty(), begin() and end(), so the same loops and algorithms work on all of them.
Objects and Classes
Objects and Algorithms · C++ 1
Classes Describe, Objects Are
A class is a blueprint: it lists the data each object carries (data members) and what each object can do (member functions). An object is one instance. string and vector are classes you have been using; now you write your own. The interface (the class definition) and the implementation (the function bodies) are usually written separately, even in one file.
The interface: what callers see
/**
A bank account has a balance that can be changed by deposits and withdrawals.
*/
class BankAccount
{
public:
/** Constructs a bank account with a zero balance. */
BankAccount();
/** Constructs a bank account with a given balance. */
BankAccount(double initial_balance);
/** Deposits money. @param amount the amount to deposit */
void deposit(double amount);
void withdraw(double amount);
/** Gets the current balance. @return the balance */
double get_balance() const;
private:
double balance; // data member: one per object
};The implementation: ClassName:: in front of every function
BankAccount::BankAccount()
{
balance = 0;
}
BankAccount::BankAccount(double initial_balance)
{
balance = initial_balance;
}
void BankAccount::deposit(double amount)
{
balance = balance + amount;
}
void BankAccount::withdraw(double amount)
{
balance = balance - amount;
}
double BankAccount::get_balance() const
{
return balance;
}Using the class
BankAccount harrys_checking; // default constructor: NO parentheses
BankAccount moms_savings(5000); // or BankAccount moms_savings{5000};
harrys_checking.deposit(2000);
moms_savings.withdraw(500);
cout << harrys_checking.get_balance() << endl; // 2000
cout << moms_savings.get_balance() << endl; // 4500The Pieces of a Class
| Piece | Looks like | Notes |
|---|---|---|
| Data member | double balance; | Always private; each object has its own copy; not initialized automatically |
| Constructor | BankAccount(double initial_balance); | Same name as the class, no return type; runs when the object is created; several may exist. Set every data member in every constructor |
| Mutator | void deposit(double amount); | Changes the object |
| Accessor | double get_balance() const; | Reports without changing; mark it const so it can be called on const objects and the compiler enforces the promise |
public: / private: | section labels | Everything after a label has that access until the next label |
| The semicolon | }; | A class definition ends with a semicolon. Forgetting it produces baffling errors on the next line |
Encapsulation
- Private data plus public functions. Callers use the functions and never see or depend on how the data is stored.
- You can change the inside later without touching the callers.
- Member functions can check their arguments:
depositcan reject a negative amount; a public variable could not.
Objects are values
BankAccount a(1000);
BankAccount b = a; // b is a COPY; two separate objects
b.deposit(500);
cout << a.get_balance() << endl; // 1000: unchanged
void show(const BankAccount& acct) // pass big objects by const reference
{
cout << acct.get_balance() << endl; // allowed because get_balance is const
}Unlike Java and Python, a C++ object variable is the object, not a reference to it. Assignment copies. To share one object between two names you pass it by reference or use a pointer.
Initializer Lists, Static Members and Design
Member initializer list
class BankAccount
{
public:
BankAccount(double initial_balance)
: balance(initial_balance), transaction_count(0) // initialize here
{
}
private:
double balance;
int transaction_count;
};
// Required for const members and members without a default constructor;
// preferred everywhere because it initializes instead of assigning.Static members
class BankAccount
{
public:
BankAccount();
static double round_cents(double x); // no object needed
private:
static int last_assigned_number; // shared by all accounts
int account_number;
double balance;
};
int BankAccount::last_assigned_number = 1000; // defined once, outside the class
BankAccount::BankAccount() : balance(0)
{
last_assigned_number++;
account_number = last_assigned_number;
}Designing a class, step by step
- 1. Write one sentence saying what an object of the class is and what it is responsible for. If that takes two sentences, you have two classes.
- 2. Start with the public interface: what should callers be able to do? Write the function headers and comments first, marking every accessor
const. - 3. Then pick the data members that make those functions possible. Fewer is better. Make every one
private. - 4. Write the constructors so that every data member is initialized, in the initializer list; C++ gives numbers no default value.
- 5. Every function should leave the object in a valid state. Test the class alone with a small
mainbefore using it elsewhere. - 6. In a bigger project the class definition goes in
bankaccount.h(guarded by#ifndef BANKACCOUNT_H/#define/#endifor#pragma once), the implementation inbankaccount.cpp, and every file that uses it says#include "bankaccount.h".
Mistakes to watch for
- The missing semicolon after
};:error: expected ';' after class definition, reported on the line after the class. - Touching a private member from outside:
error: 'double BankAccount::balance' is private within this context. Go through a public member function. - Changing a member inside a
constfunction:error: assignment of member 'BankAccount::balance' in read-only object. Calling a non-const function on aconst BankAccount&:error: passing 'const BankAccount' as 'this' argument discards qualifiers. Mark every accessorconst. - A static data member declared in the class but never defined outside it: the compiler is happy, then the linker says
undefined reference to 'BankAccount::last_assigned_number'. Add theint BankAccount::last_assigned_number = 1000;line in the.cppfile. - A data member left out of the constructor holds garbage, not zero; printing it shows a different number each run. The initializer list should name every member.
Inheritance
Objects and Algorithms · C++ 1
Deriving a Class
Inheritance builds a new class from an existing one. The derived class gets every public member of the base class and adds or changes what it needs. Read class SavingsAccount : public BankAccount as “a SavingsAccount is a special kind of BankAccount”.
savingsaccount.cpp
class SavingsAccount : public BankAccount
{
public:
SavingsAccount(double rate);
void add_interest();
private:
double interest_rate; // added to what BankAccount has
};
SavingsAccount::SavingsAccount(double rate)
: BankAccount(), interest_rate(rate) // base class constructor first
{
}
void SavingsAccount::add_interest()
{
double interest = get_balance() * interest_rate / 100;
deposit(interest); // inherited functions, called directly
}What the derived class can see
| Modifier | Who can use it |
|---|---|
public | Everyone |
protected | The class and its derived classes |
private | The class itself only. A derived class cannot touch the base class’s private members; it goes through the inherited public functions. |
Overriding
class CheckingAccount : public BankAccount
{
public:
CheckingAccount();
void deposit(double amount); // same header: replaces the inherited one
private:
int transaction_count;
};
void CheckingAccount::deposit(double amount)
{
transaction_count++;
BankAccount::deposit(amount); // then do what the base class does
}Polymorphism Needs virtual and References or Pointers
This is the C++ twist. For the object’s version of a function to run when you hold it through a base-class reference or pointer, the function must be declared virtual in the base class. And because objects are values, you cannot put a SavingsAccount into a BankAccount variable without slicing off its extra parts; you work through pointers or references instead.
class BankAccount
{
public:
virtual void deposit(double amount); // virtual: pick the version at run time
virtual void print() const;
virtual ~BankAccount() {} // always a virtual destructor in a base class
// ...
};
class CheckingAccount : public BankAccount
{
public:
void deposit(double amount) override; // override: compiler checks the header matches
void print() const override;
};
vector<BankAccount*> accounts; // pointers, so no slicing
accounts.push_back(new BankAccount(100));
accounts.push_back(new SavingsAccount(2.5));
accounts.push_back(new CheckingAccount());
for (BankAccount* acct : accounts)
{
acct->deposit(10); // the object's own version runs because deposit is virtual
acct->print();
}
for (BankAccount* acct : accounts) { delete acct; } // what you new, you deleteSlicing
SavingsAccount s(2.5);
BankAccount b = s; // COPIES only the BankAccount part: slicing
BankAccount& r = s; // a reference: still the whole SavingsAccount
BankAccount* p = &s; // a pointer: same
r.deposit(10); // SavingsAccount's version if deposit is virtualRules of thumb
- Mark a function
virtualin the base class when derived classes may replace it;virtualis inherited, sooverridein the derived class is enough there. - Give every base class a
virtualdestructor, sodeletethrough a base pointer destroys the whole object. - Prefer
unique_ptr<BankAccount>from<memory>to rawnew/deleteonce your course covers it:auto p = make_unique<SavingsAccount>(2.5);deletes itself. dynamic_cast<SavingsAccount*>(acct)returns the pointer if the object really is a SavingsAccount, ornullptr: the C++instanceof.
Abstract Classes
class Shape
{
public:
Shape(const string& name) : name(name) {}
virtual ~Shape() {}
string get_name() const { return name; }
virtual double area() const = 0; // pure virtual: derived classes MUST define it
void describe() const
{
cout << name << " with area " << area() << endl;
}
private:
string name;
};
class Circle : public Shape
{
public:
Circle(double r) : Shape("circle"), r(r) {}
double area() const override { return 3.14159 * r * r; }
private:
double r;
};
Shape s("x"); // error: cannot create an object of an abstract class
Circle c(2);
c.describe(); // circle with area 12.5664A class with at least one pure virtual function (= 0) is abstract: it exists to be derived from. A class made only of pure virtual functions plays the role of a Java interface. The exact message for Shape s("x") is error: cannot declare variable 's' to be of abstract type 'Shape'; you also get it for Circle if its area is misspelled or missing const, because the pure virtual function is then still unimplemented.
Mistakes to watch for
- Forgetting
virtualin the base class:Shape& r = c; r.describe()calls the base version with no warning. Mark the base functionvirtualand writeoverrideon every derived one, so a misspelled override iserror: ... marked 'override', but does not overrideinstead of a silent new function. - Copying a derived object into a base variable (
Shape s = c;) slices it: the derived part is cut off and the base version runs even withvirtual. Polymorphism needs a reference or a pointer. - The base class has a constructor with parameters and the derived constructor does not call it:
error: no matching function for call to 'Shape::Shape()'. Add: Shape(args)to the derived constructor’s initializer list.
Recursion
Objects and Algorithms · C++ 1
A Function That Calls Itself
A recursive function solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case answered directly, and a recursive case that moves toward the base case.
Factorial
long long factorial(int n)
{
if (n <= 1) // base case
{
return 1;
}
return n * factorial(n - 1); // recursive case: smaller n
}
// factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24Sum of digits
int digit_sum(int n)
{
if (n < 10) { return n; }
return digit_sum(n / 10) + n % 10;
}
// digit_sum(1729) = digit_sum(172) + 9 = (digit_sum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19Palindrome
bool is_palindrome(const string& s)
{
if (s.length() <= 1) { return true; }
if (s[0] != s[s.length() - 1]) { return false; }
return is_palindrome(s.substr(1, s.length() - 2));
}Thinking recursively
- Trust the recursive call. Assume
is_palindromeworks for shorter strings; your job is only the first and last letter. - Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
- Trace tiny inputs by hand: the empty string, one character, two characters.
Writing a recursive function, step by step
- 1. State the contract in one line: “
digit_sum(n)returns the sum of the digits of n”. Everything below relies on it. - 2. Find the smallest input(s) and return the answer directly. For
digit_sumthat is a single digit; for strings and vectors it is usually length 0 or 1. - 3. For any bigger input, peel off one piece (
n % 10,s[0],v[n - 1]) and assume the function already works on what is left. - 4. Combine the piece with that result, and
returnit. - 5. Check that every recursive call is strictly smaller and cannot skip past the base case (negative numbers, odd lengths).
- 6. Test the base case first, then one step above it, then something larger.
Mistakes to watch for
- No base case, or one the input never reaches (
factorial(-1)withif (n == 0)): the program dies withSegmentation faultwhen the stack runs out, after some tens of thousands of calls. g++ warns about the obvious version:warning: infinite recursion detected. - Forgetting
returnbefore the recursive call: the call runs, its result is dropped, and the caller gets garbage, with onlywarning: control reaches end of non-void functionto tell you. - Overflow:
factorial(13)as anintprints1932053504, not 6227020800. Uselong long, which lasts untilfactorial(20). - Calling with the same argument (
digit_sum(n)instead ofdigit_sum(n / 10)). The input must shrink on every call.
When Recursion Is Slow
// Fibonacci the obvious way: correct, but fib(45) makes over a billion calls
long long fib(int n)
{
if (n <= 2) { return 1; }
return fib(n - 1) + fib(n - 2);
}
// The same numbers with a loop: n steps
long long fib_loop(int n)
{
if (n <= 2) { return 1; }
long long older = 1, old = 1, result = 1;
for (int i = 3; i <= n; i++)
{
result = old + older;
older = old;
old = result;
}
return result;
}- When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop, or remember results you have already computed in a vector (memoization).
- Each call uses stack memory. Recursing a few hundred thousand levels deep crashes with a stack overflow (a segmentation fault, with no friendly message); a loop would not.
- Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, trees, and “try every choice” searches.
Permutations and Towers of Hanoi
All permutations of a string
vector<string> permutations(const string& word)
{
vector<string> result;
if (word.length() == 0)
{
result.push_back(word); // one permutation of the empty string
return result;
}
for (size_t i = 0; i < word.length(); i++)
{
string shorter = word.substr(0, i) + word.substr(i + 1);
for (const string& p : permutations(shorter))
{
result.push_back(word[i] + p);
}
}
return result;
}Towers of Hanoi
// Move n disks from peg "from" to peg "to", using "via" as the spare
void hanoi(int n, const string& from, const string& to, const string& via)
{
if (n == 0) { return; }
hanoi(n - 1, from, via, to);
cout << "Move disk " << n << " from " << from << " to " << to << endl;
hanoi(n - 1, via, to, from);
}
// hanoi(3, "A", "C", "B") prints 7 moves; n disks take 2^n - 1Mutual recursion is two functions that call each other, such as an expression evaluator where expression() calls term(), which calls factor(), which calls expression() again for a parenthesized part. Because C++ must see a function before it is called, one of them needs a prototype above the other.
Sorting and Searching
Objects and Algorithms · C++ 1
Selection Sort and Insertion Sort
Selection sort
void selection_sort(vector<int>& a)
{
for (size_t i = 0; i + 1 < a.size(); i++)
{
size_t min_pos = i; // find the smallest in a[i..]
for (size_t j = i + 1; j < a.size(); j++)
{
if (a[j] < a[min_pos]) { min_pos = j; }
}
swap(a[i], a[min_pos]); // swap it into position i
}
}Insertion sort
void insertion_sort(vector<int>& a)
{
for (size_t i = 1; i < a.size(); i++)
{
int next = a[i]; // a[0..i-1] is already sorted
size_t j = i;
while (j > 0 && a[j - 1] > next) // slide bigger ones right
{
a[j] = a[j - 1];
j--;
}
a[j] = next; // drop next into the gap
}
}Watch them work
Print the vector as the last line of the outer loop (cout << "pass " << i + 1 << ":", then each element) and run each on {11, 9, 17, 5, 12}:
selection sort insertion sort
pass 1: 5 9 17 11 12 pass 1: 9 11 17 5 12
pass 2: 5 9 17 11 12 pass 2: 9 11 17 5 12
pass 3: 5 9 11 17 12 pass 3: 5 9 11 17 12
pass 4: 5 9 11 12 17 pass 4: 5 9 11 12 17Selection sort grows the sorted part from the left by picking the smallest remaining value each pass; insertion sort grows it by sliding the next value into place. Both make about n²/2 comparisons: doubling the vector quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work. Note the vectors are passed by reference (&) so the caller’s data is what gets sorted.
Mistakes to watch for
- Leaving out the
&:void selection_sort(vector<int> a)sorts a copy and the caller’s vector is untouched. No message, just unsorted output. i < a.size() - 1withsize_t: on an empty vectorsize() - 1wraps around to a huge number and the loop runs off the end. Writei + 1 < a.size(), as above.- Inner loop with
j <= a.size(): one position past the end, read without any check. Positions end atsize() - 1. - Swapping without
swapor a temporary:a[i] = a[min_pos]; a[min_pos] = a[i];copies one value into both slots.
Merge Sort
void merge(vector<int>& a, int from, int mid, int to)
{
vector<int> merged;
int i = from, j = mid + 1;
while (i <= mid && j <= to)
{
if (a[i] < a[j]) { merged.push_back(a[i]); i++; }
else { merged.push_back(a[j]); j++; }
}
while (i <= mid) { merged.push_back(a[i]); i++; }
while (j <= to) { merged.push_back(a[j]); j++; }
for (size_t k = 0; k < merged.size(); k++) { a[from + k] = merged[k]; }
}
void merge_sort(vector<int>& a, int from, int to)
{
if (from >= to) { return; }
int mid = (from + to) / 2;
merge_sort(a, from, mid); // sort each half
merge_sort(a, mid + 1, to);
merge(a, from, mid, to); // then merge them
}
// call: merge_sort(values, 0, values.size() - 1);| Algorithm | Comparisons for n items | Big-O | Doubling n makes it |
|---|---|---|---|
| Selection sort | about n²/2 | O(n²) | 4 times slower |
| Insertion sort | n²/4 average; n if already sorted | O(n²) | 4 times slower |
| Merge sort | about n log2 n | O(n log n) | a little more than 2 times slower |
std::sort (introsort) | n log n | O(n log n) | a little more than 2 times slower |
| Linear search | n/2 average, n worst | O(n) | 2 times slower |
| Binary search (sorted data) | about log2 n | O(log n) | one more step |
Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.
Searching
Linear search
int linear_search(const vector<int>& a, int value)
{
for (size_t i = 0; i < a.size(); i++)
{
if (a[i] == value) { return i; }
}
return -1;
}Binary search (the vector must be sorted)
int binary_search_pos(const vector<int>& a, int value)
{
int low = 0;
int high = a.size() - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == value) { return mid; }
else if (a[mid] < value) { low = mid + 1; }
else { high = mid - 1; }
}
return -1;
}
// 1,000,000 sorted items: at most 20 stepsThe library does it faster: use these in real programs
#include <algorithm>
sort(values.begin(), values.end()); // ascending
sort(values.begin(), values.end(), greater<int>()); // descending
bool found = binary_search(values.begin(), values.end(), 42); // sorted data only
auto it = lower_bound(values.begin(), values.end(), 42); // first position not less than 42
int pos = it - values.begin();
sort(names.begin(), names.end(),
[](const string& a, const string& b) { return a.length() < b.length(); }); // by another rule
sort(accounts.begin(), accounts.end(),
[](const BankAccount& x, const BankAccount& y) { return x.get_balance() > y.get_balance(); });Sorting your own objects
class Country
{
public:
double get_area() const { return area; }
bool operator<(const Country& other) const // defines the natural order
{
return area < other.area;
}
private:
string name;
double area;
};
// Then sort(countries.begin(), countries.end()) just works.operator< vs a comparison function
operator<in the class gives one natural order thatsort,set,map,minandmaxall use.- A lambda or comparison function passed to
sortpicks a different order for one call, without touching the class. - Comparison functions must return
trueonly when the first argument comes strictly before the second; never use<=.