C++ Tutorial

C++ Algorithms

sort, find, count, and accumulate work on ranges. Include <algorithm>.

A range is two iterators

The algorithms in the standard library do not take a container by name. They take a half-open range: the first iterator, then the iterator one past the last element. For a vector that pair isv.begin() and v.end(). The same functions work on an array if you pass pointers to the first element and one past the last.

Include <algorithm> for sort, find, and count. Include<numeric> for accumulate. Include <vector> when the data lives in a vector. StudyGrid compiles these examples as C++17 with g++ 13.

sort rearranges the range

sort(first, last) orders the elements from smallest to largest using <. After the call, the vector itself is changed. There is no separate sorted copy unless you make one first.

Example

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> temps = {18, 7, 21, 12, 9};
  sort(temps.begin(), temps.end());
  for (int t : temps) {
    cout << t << " ";
  }
  cout << endl;
  return 0;
}

Output is 7 9 12 18 21. begin() is the first slot. end() is not a value in the vector; it marks the stop. Every algorithm in this chapter uses that pair.

find locates one value

find(first, last, value) walks the range until it sees value. It returns an iterator to that element. If the value is missing, the return is last — for a vector, that isv.end(). Always test against end() before you dereference.

Example

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> lots = {11, 42, 8, 19, 5};
  vector<int>::iterator it = find(lots.begin(), lots.end(), 42);
  if (it != lots.end()) {
    cout << "found " << *it << endl;
  } else {
    cout << "missing" << endl;
  }
  return 0;
}

*it is the int sitting at that iterator. Change 42 to 99 and the program prints missing. find stops at the first match; it does not count the rest.

count tallies matches

count(first, last, value) returns how many times value appears. The return type is an integer count, not an iterator. Use it when you care about frequency, not position.

Example

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> rolls = {3, 1, 3, 3, 6, 3};
  int threes = count(rolls.begin(), rolls.end(), 3);
  int sixes = count(rolls.begin(), rolls.end(), 6);
  cout << "threes: " << threes << endl;
  cout << "sixes: " << sixes << endl;
  return 0;
}

Output is threes: 4 then sixes: 1. A missing value yields 0, not an error.

accumulate lives in numeric

accumulate is not in <algorithm>. Include <numeric>. The call is accumulate(first, last, start). It adds every element onto start and returns the total. For a sum of int values, start at 0.

Example

#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int main() {
  vector<int> crates = {4, 6, 5, 7};
  int total = accumulate(crates.begin(), crates.end(), 0);
  cout << "sum: " << total << endl;
  cout << "count: " << crates.size() << endl;
  return 0;
}

Output is sum: 22 and count: 4. The third argument is the seed, not an extra element. Starting at 10 would print 32. For a product, the seed is 1 and you pass a multiplying function; this chapter stays with addition.

begin and end on a vector

CallHeaderReturns
sort(b, e)<algorithm>void; rearranges in place
find(b, e, v)<algorithm>iterator, or e if missing
count(b, e, v)<algorithm>how many times v appears
accumulate(b, e, 0)<numeric>the running total

Write nums.begin() and nums.end() every time. Do not pass the vector itself to these four functions in C++17. A later standard adds range overloads; this tutorial stays with iterators so the same pattern works on arrays and vectors.

Write a loop only when you must

A hand-written for that finds a max or a sum is fine while you learn. Once the work is “sort this” or “how many of these”, prefer the named algorithm. The range is obvious. Off-by-one mistakes shrink.

Open an example with Try it in C++ at /cpp/try. Next: lambdas, so you can pass a custom comparison into sort without writing a named function.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Statistics

Sort, then the median-ish middle

Five marks sorted: 64, 72, 77, 81, 90. The middle value is 77, the median for an odd count. sort from <algorithm> is the tool; writing bubble sort here would hide the statistics.

median of sorted x₁…xₙ (n odd) = x₍ₙ₊₁₎/₂

Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  vector<int> marks = {72, 81, 64, 90, 77};
  sort(marks.begin(), marks.end());
  cout << "median = " << marks[marks.size() / 2] << endl;
  return 0;
}

Physics

Hottest temperature with max_element

The same five logger values peak at 19.1 °C. max_element returns an iterator. Dereference it. Walking the list yourself is the arrays chapter; this is the library doing that walk.

Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  vector<double> celsius = {18.2, 18.5, 19.0, 18.8, 19.1};
  cout << "hottest = " << *max_element(celsius.begin(), celsius.end()) << " C" << endl;
  return 0;
}

FAQ: C++ Algorithms

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ algorithms examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ algorithms in this C++ C++ lesson (C++ Algorithms).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.