Beginner C ++: Converting Index Syntax to Iterator Syntax

I'm trying to learn C ++ with a little Java background, and I'm trying to write code that returns the intersection of two lists. I believe that I have the right idea conceptually, but I am having problems with the syntax because nothing compiles.

Here is the code I came up with:

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

template <typename Object>
list<Object> intersection( const list<Object> & L1, const list<Object> & L2){

  std::list<Object> result;                 
  int pos1 = 0;
  int pos2 = 0;

  while (pos1 < L1.size() && pos2 < L2.size()) {
    if (L1[pos1] > L1[pos2]) {
      pos1++;
    } else if (L2[pos2] > L1[pos1]) {
      pos2++;
    } else {
      result.push_back(L2[pos2]);
      pos1++;
      pos2++;
    }
  }
  return result;

}

It seems to me what I need: an iterator (I'm sure the way to access the list is wrong)

+5
source share
2 answers

Change pos1 and pos2 to iterators:

list<Object> intersection( const list<Object> & L1, const list<Object> & L2){
  std::list<Object> result;                 
  std::list<Object>::iterator pos1 = L1.begin(), pos2 = L2.begin();
  while (pos1 != L1.end() && pos2 != L2.end()) {
     if (*pos1 > *pos2) { //works only if pos1 != L1.end() and pos2 != L2.end()
       pos1++;
       ...

pos1 = L1.begin()points pos1to the first element of L1.

++pos1 moves the iterator forward to the next element

*pos1 gets the item from pos1

pos1 != L1.end() , pos1 . pos1, pos1 == L1.end().

+4

const_iterator iterator.

++ typedef , , , , , .

list<Object>::value_type Object. :

list<Object>::value_type object = Object();

list<Object>::iterator - , . , , begin() end().

const, , begin iterator, const_iterator. iterator. , , - .

, const_iterator. .

+2

All Articles