Adding values in a list with an iterator

Aug 12, 2018 at 2:06am
I'm looking to take the list and instead of going from 0-90 by 10 I would like it to go from 0-90 counting by 5's.

However I messed up in my fives_list function and am not getting desired output. The output I'm getting is:

0 5 10 5 15 20 5 15 25 30 5 15 25 35 40 5 15 25 35 45 50 5 15 25 35 45 55 60 5 15 25 35 45 55 65 70 5 15 25 35 45 55 65 75 80 5 15 25 35 45 55 65 75 85 90

With the node list being 55 when it should be 19 total nodes. I'm unsure how to fix this any help is appreciated.
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
  void populate_list(list<int> &myList);
void fives_list(list<int> &myList);
void display_list(list<int> &myList);
void remove_ends(list<int> &myList);


int main()
{   //define empty list
    list<int> myList;

    populate_list(myList);
    display_list(myList);

    cout << endl;

    fives_list(myList);
    display_list(myList);

    cout << endl;



    return 0; 
}

void populate_list(list<int> &myList)
{
    //add values to list
    for(int x = 0; x < 100; x += 10)
    {
        myList.push_back(x);
    }
}

void display_list(list<int> &myList)
{
    for (auto  it = myList.begin(); it != myList.end(); it++)
    {
        cout << *it << " ";
    }

    cout << endl;

    cout << "The number of nodes in the list is: " << myList.size();
}

void fives_list(list<int> &myList)
{
    for(int i = 5; i <= 85; i += 10)
    {
        for (auto it = myList.begin(); it != myList.end(); it++)
        {
            if(*it >= i)
            {
                myList.insert(it, i);
            }
        }
    }
}
Aug 12, 2018 at 2:19am
You just need a break after the insert so that you only insert the value in the first position where it's greater.
Aug 12, 2018 at 2:30am
Oh wow that was an easy fix thank you very much!
Topic archived. No new replies allowed.