Skip to content

Beginner Gotchas

The Number Strings That Sorted Like Words

the values look numeric, but their type is text

int main() {
  std::vector<std::string> ids{"2", "10", "1"};
  std::sort(ids.begin(), ids.end());

  std::cout << ids[0] << ' ' << ids[1] << ' ' << ids[2] << '\n';
}

Run it. Does the order come out as 1, 2, 10?

Answer
1 10 2

The strings were sorted lexicographically, not numerically.

Why

The default comparison for std::sort is the type's < operator. std::string compares lexicographically, so both strings beginning with '1' come before the one beginning with '2', and the shorter prefix "1" comes first. GCC emits no warning under -Wall -Wextra.

The fix

Parse numeric input at the boundary and keep it numeric:

std::vector<int> ids{2, 10, 1};
std::sort(ids.begin(), ids.end());

Takeaway: std::sort follows the stored type; parse number-like strings before sorting them.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry