Adding value to list element

Hello need help with this question:

Use the previously filled containers and add one to every element’s value. While the vector and deque containers support array subscript notation (objectname[index]), the list container does not. Use an iterator and deferencing to traverse the list elements. The following creates an iterator on the list data structure where l is the name of the list:

list<long>::iterator it = l.begin();

Use it as if it is a pointer to the list.

The vector and deque was easy but I just can't do the list one.
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
#include <iostream>
#include <list>
#include <iterator>
using namespace std;

int main()
{
    list<long> mylist;                         
    int a = 1;
    for (int i = 0; i < 10; i++)
    {
        mylist.push_back(a);
        a++;
    }
    list<long>::iterator it = mylist.begin();
    for (int p = 0; p < 10; p++)
    { 
        //???????????
        //*it + p  += 1;     - want to do this, but left can only have one value
    }
    for (int p = 0; p < 10; p++)
    {
        cout << *it+p;
    }
    
    return 0;
}
Maybe like this:
1
2
3
4
5
6
// add 1 to every elem in the list
  while (it != mylist.end())
  {
    *it = *it + 1;
    ++it; // move to next 
  }
You were very close, you had the right idea. A modified for loop using an iterator is what you want:
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
#include <iostream>
#include <list>
// #include <iterator>

int main()
{
   std::list<long> mylist;

   for (int i { }; i < 10; i++)
   {
      mylist.push_back(i);
   }

   for (std::list<long>::const_iterator itr { mylist.cbegin() }; itr != mylist.cend(); itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

   for (std::list<long>::iterator itr { mylist.begin() }; itr != mylist.end(); itr++)
   {
      *itr += 1;
   }

   // instead of typing the iterator type use auto
   // the compiler selects the appropriate type
   // use const iterators if you have no need to modify the list's elements
   for (auto itr { mylist.cbegin() }; itr != mylist.cend(); itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

   // let's use a range based loop for the output
   for (const auto& itr : mylist)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Do note the differences of how the list's elements are accessed when using an iterator vs. using a range-based for loop.
Last edited on
I got it. Thank you so much.
Topic archived. No new replies allowed.