C++ Tutorial

C++ Set

set stores unique values in order. Insert, count, and iterate without duplicates.

Unique values, kept in order

A set is a collection that refuses duplicates and keeps its values sorted. Think of it as amap with only keys: membership, not a payload. Include <set>. The type isset<int> or set<string>.

Use it when the question is “have I already seen this?” or “give me these values once each, sorted.” A vector can hold the same number twice. A set will not.

insert

insert adds a value when it is new. size() is how many unique values you have. After two different inserts, size is 2.

Example

#include <iostream>
#include <set>
using namespace std;

int main() {
  set<int> seen;
  seen.insert(4);
  seen.insert(1);
  cout << seen.size() << endl;
  return 0;
}

Output is 2.

Click Try it in C++ under the example. That opens /cpp/try. This is not the Python editor at /try.

Duplicates are ignored

Insert the same value again and the set stays the same. There is no error and no extra element. That silence is the feature: you can insert every number you see in a stream and end with the distinct ones.

Example

#include <iostream>
#include <set>
using namespace std;

int main() {
  set<int> seen;
  seen.insert(4);
  seen.insert(1);
  seen.insert(4);
  seen.insert(1);
  seen.insert(4);
  cout << seen.size() << endl;
  for (int n : seen) {
    cout << n << " ";
  }
  cout << endl;
  return 0;
}

Output is 2 on the first line, then 1 4. Five inserts, two values, printed in sorted order — not the order of the first insert.

count

count(value) returns 1 if the value is in the set and 0 if it is not. Like map, a set stores each value at most once, so the result is never greater than 1. Use it as a yes-or-no test before you rely on the value being there.

Example

#include <iostream>
#include <set>
using namespace std;

int main() {
  set<int> allowed;
  allowed.insert(200);
  allowed.insert(201);
  allowed.insert(204);
  cout << allowed.count(200) << endl;
  cout << allowed.count(404) << endl;
  return 0;
}

Output is 1 then 0. Status 200 is allowed. 404 is not in the set.

Iterate

Range-for walks the set from smallest to largest. For int that is numeric order. Forstring it is lexicographic order. There is no index; you do not write seen[0].

Example

#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
  set<string> tags;
  tags.insert("stl");
  tags.insert("map");
  tags.insert("set");
  tags.insert("map");
  cout << tags.size() << endl;
  for (const string& tag : tags) {
    cout << tag << endl;
  }
  return 0;
}

Size is 3 because the second "map" was ignored. The loop printsmap, then set, then stl.

set versus vector

vector<T>set<T>
DuplicatesAllowedSilently ignored
Order in a loopInsertion orderSorted
LookupIndex, or scancount by value
Index [i]YesNo

Keep a vector when position matters or when the same value may appear twice on purpose. Switch to a set when uniqueness is the rule you want the type to enforce.

What comes after set

You now have the three containers this track emphasizes: vector, map, andset. The next chapter stays in the STL and looks at more algorithms: sort you already saw, then count and friends on a range.

None of these programs read or write files. They compile with g++ in /cpp/try and on Compiler Explorer.

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.

Biology

Unique bases in a motif

DNA uses A, T, C, G. Inserting A T G C C A T into a set leaves four values. Duplicates vanish. That is not a sequence any more — order of first appearance is lost — it is the alphabet of the strand.

Example

#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
  set<char> bases;
  string dna = "ATGCCAT";
  for (char b : dna) bases.insert(b);
  for (char b : bases) cout << b;
  cout << endl;
  return 0;
}

Maths

Unique marks

3, 1, 3, 2 stored in a set print as 1 2 3. The second 3 is dropped. Sets answer “have I seen this value?” with count, in log time.

Example

#include <iostream>
#include <set>
using namespace std;

int main() {
  set<int> nums = {3, 1, 3, 2};
  for (int n : nums) cout << n << " ";
  cout << endl;
  return 0;
}

FAQ: C++ Set

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++ set 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++ set in this C++ C++ lesson (C++ Set).

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.