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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

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 Oct 8, 2025 by avibootz
edited Oct 8, 2025 by avibootz
...