Skip to content

Last updated:2026-10-12

C++ Short URL Service Demo

Real short URL services are relatively complex, involving things like hash algorithms and number-dispatching systems.

Today we are simply simulating a short URL implementation from the perspective of a small project.

How can you quickly implement one in just a few dozen lines of code? The key points involved are:

  • How to shorten a long URL
  • How to store the mapping relationship

The mapping relationship goes without saying — just use a map persisted in memory. If a database is involved, you need to write it into the database through interfaces such as the database's JDBC/ODBC.

For shortening the long URL, a random algorithm plus fixed-length approach is adopted here.

1. Randomness

Use uniform_int_distribution to generate a random number in the [a, b] interval. Here we randomly pick one character at a time from the string below, and the final concatenation is the short URL.

string characters{
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};

It contains:

  • digits
  • lowercase letters
  • uppercase letters
uniform_int_distribution<int> distribution(0, characters.size() - 1);
string code;
for (int i = 0; i < length; ++i)
  code += characters[distribution(generator)];

2. Storage

Just store it in a map each time, for example:

if (links.count(originalLink)) {
  return links[originalLink];
}

shortCode = generateRandomCode(len);
string shortenedLink = base_url + shortCode;
links[shortenedLink] = originalLink;

The base URL is kept here, for example:

string baseUrl = "https://www.google.com.hk/search";
LinkShortener shortener(baseUrl);

string originalLink = "https://www.google.com.hk/search?q=asdsad&oq=asdsad&aqs=chrome.0.69i59j69i57j69i59l2.634j0j4&sourceid=chrome&ie=UTF-8";
string shortenedLink = shortener.shortenLink(originalLink, 8);

Finally, this URL can be shortened to:

https://www.google.com.hk/searchtXuOlOSt

Isn't that simple? The tests and complete code for this section have been updated in the Knowledge Planet community. Welcome to join and learn together~

Comments