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.
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:
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~
Related Topics¶
- Hand-Writing C++ FnOnce | C++那些事
- A Small C++ gRPC Project | C++那些事
- C++ Inter-Process Communication in Practice | C++那些事
- C++17 and SQLite Folder Size Statistics | C++那些事
- Google Benchmark Performance Testing | C++那些事
- C++20 Coroutine HTTP Server | C++那些事
- Protobuf ZeroCopy Serialization | C++那些事
- Accelerating Python with pybind11 | C++那些事
- C++ Stack Calculator Design | C++那些事