How to create a vector with random HEX RGB color codes in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <random>
#include <iomanip> // For formatting hex output // setw // setfill

// Function to generate a random RGB color
std::string generateRandomColor() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(0, 255);

    // Generate random values for R, G, and B
    int red = dist(gen);
    int green = dist(gen);
    int blue = dist(gen);

    // Format the color as a hex string (e.g., #RRGGBB)
    std::ostringstream colorStream;
    colorStream << "#" << std::hex << std::setw(2) << std::setfill('0') << red
                << std::setw(2) << std::setfill('0') << green
                << std::setw(2) << std::setfill('0') << blue;

    return colorStream.str();
}

// Function to create a vector of random color codes
std::vector<std::string> generateRandomHEXRGBColorVectorSize(int size) {
    std::vector<std::string> colors;

    for (int i = 0; i < size; ++i) {
        colors.push_back(generateRandomColor());
    }

    return colors;
}

int main() {
    int vectorSize = 5;

    if (vectorSize <= 0) {
        std::cerr << "Invalid size. Please enter a positive integer." << std::endl;
        return 1;
    }

    std::vector<std::string> randomColors = generateRandomHEXRGBColorVectorSize(vectorSize);

    std::cout << "Generated Random Colors:" << std::endl;
    for (const auto& color : randomColors) {
        std::cout << color << std::endl;
    }
}


/*
run:

Generated Random Colors:
#750576
#e0268e
#4170e6
#e6e4c4
#82152a

*/

 



answered 8 hours ago by avibootz
edited 4 hours ago by avibootz
...