a little help please

Pages: 123
Zeroes, catfish3 are you guys here? I'm sorry to bother you but I need to ask you guys one small thing: if I wanted to write numbers from lowest to highest and not vice versa, which part of the code would I edit?
I've made some changes... because for some reason you ignore the descending order part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    srand(time(NULL));

    vector<int> numbers;

    for (int i = 0; i != 10; ++i)
    {
        int randomInt = rand() % 20 + -10;
        cout << randomInt << ' ';
        numbers.push_back(randomInt);
    }

    cout << "\n=====================================\n";
    sort(numbers.rbegin(), numbers.rend());

    for (int i =0; i != numbers.size(); ++i)
        cout << numbers[i] << ' ';

    cout << "\n=====================================\n";

    int second;
    int index = 1;

    while (true)
        if (numbers[index] == numbers[index-1])
            index++;
        else
        {
            second = numbers[index];
            break;
        }

    cout << "Second Largest: " << second << endl;
    system("pause");
    return 0;
}
thanks
The current code, that I've given in the previous post, sorts the numbers vector in descending order -- as your assignment seems to ask.

You might want to change:

int randomInt = rand() % 20 + -10;

to

int randomInt = rand() % 21 + -10;

... if you want to include the number 10 as possible numbers.
In this regard, your original code with lowest and highest boundaries was better, because you had better control over the min/max limits.

Also suggest using at().
1
2
3
4
5
6
7
8
    while (true)
        if (numbers.at(index) == numbers.at(index-1))
            index++;
        else
        {
            second = numbers.at(index);
            break;
        }


Finally, not to scare you, but you'll be in a little trouble if you actually were required to write your own sorting function. Be mentally prepared for that possible moment, and to defend the usage of std::sort(), which is what a proficient C++ programmer would use.
Last edited on
Topic archived. No new replies allowed.
Pages: 123