Use iterator to change all elements in a list : list iterator « List « C++






Use iterator to change all elements in a list

  
 

#include <iostream>
#include <list>
using namespace std;

int main()
{
  list<int> lst; // create an empty list
  int i;

  for(i=0; i<10; i++) lst.push_back(i);

  cout << "Size = " << lst.size() << endl;

  cout << "Contents: ";
  list<int>::iterator p = lst.begin();
  while(p != lst.end()) {
    cout << *p << " ";
    p++;
  }
  cout << "\n\n";

  // change contents of list
  p = lst.begin();
  while(p != lst.end()) {
    *p = *p + 100;
    p++;
  }

  cout << "Contents modified: ";
  p = lst.begin();
  while(p != lst.end()) {
    cout << *p << " ";
    p++;
  }

  return 0;
}
/* 
Size = 10
Contents: 0 1 2 3 4 5 6 7 8 9

Contents modified: 100 101 102 103 104 105 106 107 108 109
 */
        
    
  








Related examples in the same category

1.Use iterator to loop through all elements in a list
2.Loop through list back and forth
3.Use reverse_iterator and iterator with list
4.Move list iterator using ++
5.Traverse a List Using an IteratorTraverse a List Using an Iterator