Help with random_shuffle

I am not getting the output i expected for the randomizing scores. Not sure why everything looks right. Any ideas.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
   vector<int>::const_iterator iter;

   cout<<"Creating a list of scores.";
   vector<int>scores;
   scores.push_back(1500);
   scores.push_back(3500);
   scores.push_back(7500);

   cout <<"\nHigh Scores:\n";

   for (iter=scores.begin();iter !=scores.end();++iter)
    {
       cout<<*iter<<endl;
    }

    cout <<"\nFinding a score.";
    int score;
    cout << "\nEnter a score to find: ";
    cin >> score;
    iter =find(scores.begin(),scores.end(),score);

    if (iter != scores.end())
    {
        cout <<"score found. \n";
    }
    else
    {
        cout << "Score not found\n";
    }
// what is wrong with this part as it is not printing out the scores.  It only print 0.

    cout << "\nRandomizing scores.";
    srand (static_cast<unsigned int>(time(0)));
    random_shuffle(scores.begin(),scores.end());
    cout <<"\nHigh Scores: \n";
    for (iter = scores.begin();iter !=scores.end();++iter);
    {
        cout << *iter <<endl;

    }
    

    cout << "\nSorting scores. ";
    sort(scores.begin(),scores.end());
    cout <<"\nHigh Scores:\n";
    for (iter = scores.begin();iter != scores.end();++iter)
    {
        cout<<*iter << endl;
    }
    return 0;
}
for (iter = scores.begin();iter !=scores.end();++iter);

there is a semicolon at the end of this line which shouldn't be there...
You would have found it yourself if you defined 'iter' in each for loop, like you should have done, instead of at the beginning of main.
Last edited on
Thanks, the book i am useing did not show you could do that. so i had no idea you could.
std::random_shuffle() is deprecated and will be removed in C++17. Instead, use std::shuffle()
http://en.cppreference.com/w/cpp/algorithm/random_shuffle

Favour range-based loops over classical loops. http://www.stroustrup.com/C++11FAQ.html#for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
#include <numeric>
#include <random>
#include <algorithm>

int main ()
{
    std::vector<int> seq(20) ;

    std::iota( std::begin(seq), std::end(seq), 30 ) ;
    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;

    std::mt19937 rng( std::random_device{}() ) ;

    for( int i = 0 ; i < 5 ; ++i )
    {
        std::shuffle( std::begin(seq), std::end(seq), rng ) ;
        for( int v : seq ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/07221e6a59dfe481
Topic archived. No new replies allowed.