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.
#include <iostream>
#include <list>
#include <iterator>
usingnamespace 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;
}
#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 (constauto& itr : mylist)
{
std::cout << itr << ' ';
}
std::cout << '\n';
}