Retrieving the first element in c++ vector

24,012

Solution 1

  Atom* first = atoms.begin(); // <== type error

This sets first equal to an iterator. You wanted to set it equal to the object the iterator points to. Try:

  Atom* first = *(atoms.begin());

or:

  Atom* first = atoms.front();

Since this is a vector of Atom*, its iterators point to Atom*s.

Solution 2

std::vector::begin doesn't return the first element of the vector, it returns an iterator (pointing to the first element) that can be used to iterate through the vector.

The method you're looking for is most likely std::vector::front().

Share:
24,012
Sebi
Author by

Sebi

Updated on September 30, 2020

Comments

  • Sebi
    Sebi over 3 years

    I have written a wrapper class to perform insertion/removal operations on a type vector. The code:

    class GenericSymbolTable {
       public:
           virtual void pushBackAtom(Atom *atom) = 0;
           virtual Atom* peekAtom(void) = 0;
           virtual Atom* getAtom(void) = 0;
    
       protected:
          ~GenericSymbolTable(void){}
    };
    
    class SymbolTable : public GenericSymbolTable {
       private:
           vector<Atom*> atoms;
    
       protected:
           ~SymbolTable(void);
    
       public:
           void pushBackAtom(Atom *atom);
           Atom* peekAtom(void);
           Atom* getAtom(void);
    };
    

    When writing the implementations for those methods the compiler throws conflicting type errors:

       Atom* SymbolTable::peekAtom(void) {
          if(atoms.empty()) {
              cout << "\t[W] Simbol table does not contain any atoms" << endl;
              return NULL;
          }
    
          Atom* first = atoms.begin(); // <== type error
          return first;
       }
    
       Atom* SymbolTable::getAtom(void) {
          if(atoms.empty()) {
              cout << "\t[W] Simbol table does not contain any atoms" << endl;
              return NULL;
          }
    
          Atom* first = atoms.begin(); // <== type error
          atoms.erase(atoms.begin());
          return first;
       }
    

    Error msg: cannot convert ‘std::vector::iterator {aka __gnu_cxx::__normal_iterator >}’ to ‘Atom*’ in initialization