-2

How can I print let's say 10 numbers using rand() then sort them by biggest?

#include <iostream>
using namespace std;

int main() {
    int b;
    cin >> b;
    srand(b);

    for (int i = 0; i < 10; i++){
       cout << rand() % 100000 << " ";
    }
}
Gosho
  • 31
  • 5
  • 3
    Store them in a vector and sort the vector. – FrankS101 Nov 12 '18 at 17:18
  • 1
    You could insert into a sorted structure (e.g., `std::multiset`) rather than sorting it after the fact. It's likely that this will be faster. – Mike Harris Nov 12 '18 at 17:26
  • @MikeHarris Actually, that's probably much slower on any common hardware… Even a (mostly unsuccessful) `std::find()` over an unsorted `std::vector` consistently beats a `std::set::find()` on my Ivy Bridge work laptop for N<=120. And, in your example, there isn't an asymptotic time advantage, so chances are the `std::vector`+`std::sort` will always win no matter how you choose N. "Processors love vectors – they send them flowers…" (Herb Sutter) – Arne Vogel Nov 13 '18 at 18:40

1 Answers1

1

You can generate an array, print it, and then sort it (and reprint it?).

Note: if true randomness is an issue for you, rand() + % is not suited.

#include <array>
#include <algorithm>
#include <iostream>

int main()
{
    std::array<int, 10> data;
    std::generate(begin(data), end(data), rand);
    for (auto n : data) {
        std::cout << n << ", ";
    }
    std::cout << '\n';

    std::sort(begin(data), end(data));
    for (auto n : data) {
        std::cout << n << ", ";
    }
    std::cout << '\n';
}

demo: http://coliru.stacked-crooked.com/a/2e62855189995ab0

Following: how could I define an operator to be able to write std::cout << data whatever the type of data is?.

YSC
  • 38,212
  • 9
  • 96
  • 149