Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to create and sort a list of random file names in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // sort
#include <random> // random_device // mt19937

// Function to generate a random string of given length
std::string generateRandomString(size_t length, std::string extension) {
    const std::string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_int_distribution<> distribution(0, characters.size() - 1);

    std::string randomString;
    for (size_t i = 0; i < length; i++) {
        randomString += characters[distribution(generator)];
    }
    return randomString + extension;
}

int main() {
    // Number of random file names to generate
    const size_t numFiles = 12;
    // Length of each random file name
    const size_t fileNameLength = 9;

    std::vector<std::string> fileNames;

    // Generate random file names
    for (size_t i = 0; i < numFiles; i++) {
        fileNames.push_back(generateRandomString(fileNameLength, ".bin"));
    }

    // Sort the file names
    std::sort(fileNames.begin(), fileNames.end());

    std::cout << "Sorted file names:\n";
    for (const auto& name : fileNames) {
        std::cout << name << '\n';
    }
}


   
/*
run:
   
Sorted file names:
0PPNVriNq.bin
3qrVVSgzN.bin
5M58DZcTP.bin
GYhF9Lw6o.bin
MrQflEbVS.bin
N0EUCcxnG.bin
NnSUM5XSD.bin
VrWgDws5G.bin
iYew9Mx5Q.bin
o6jRfeGHl.bin
rVm3UWl5g.bin
vNyoUkEQk.bin
   
*/

 



answered Apr 18, 2025 by avibootz
...