1

I am creating a Set class using the standard list container. When I declare the list iterator iter, I get an error:

C3861 'iter':identifier not found

I have found a few examples of other people declaring list iterators in this way, but I may be misunderstanding something about iterators.

#include <list>
#include <iterator>

using namespace std;

template <typename T>
class Set
{
private:
    list<T> the_set;
    list<T>::iterator iter;
public:
    Set() {}
    virtual ~Set() {}

    void insert(const T& item) {
        bool item_found = false;
        for (iter = the_set.begin(); iter != the_set.end(); ++iter) {
            if (*iter == item) item_found = true;
        }
        if (!item_found) {
            iter = the_set.begin();
            while (item > *iter) {
                ++iter;
            }
            the_set.list::insert(iter, item);
        }
    }
}

The error is shown happening at the line:

list<T>::iterator iter;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jgashler
  • 13
  • 4
  • Recommended reading: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – ChrisMM Jul 31 '21 at 00:30
  • Removing the 'using' statement and inserting std:: in the correct places may be a "better practice", but it doesn't change the performance of the code at all. – jgashler Jul 31 '21 at 00:37
  • On a side note: you don't need `#include ` in this code, and `the_set.list::insert()` should be just `the_set.insert()` – Remy Lebeau Jul 31 '21 at 01:50

1 Answers1

2

The compiler gets confused by that line because it doesn't know what list<T> will be before actually specializing the class with some T.

More formally you would say that list<T>::iterator is a dependent name.

The solution is to add a hint in form of the typename keyword to specify that the construct will refer to some type after all.

I.e. this should help:

    typename list<T>::iterator iter;
Yirkha
  • 12,737
  • 5
  • 38
  • 53
  • Thank you for the explanation. This fixed it :) – jgashler Jul 31 '21 at 00:41
  • See [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – Remy Lebeau Jul 31 '21 at 01:48