Search code examples
c++pointerslistiterator

How to make a pointer iterator?


For some reason I can't make a pointer iterator. Is it disabled? I tried to do it but it doesn't work...

#include <iostream>
#include <list>
#include <vector>
#include <string>

template<class T>
void convertListToVector(std::list<T> *listItem) {
typename std::list<T>::iterator it;
for (it = *listItem->begin(); it != *listItem->end(); it++)
        std::cout << *it <<std::endl;
}

int main()
{
    std::list<std::string> listExample;
    listExample.push_back("2");
    listExample.push_back("3");
    listExample.push_back("5");
    convertListToVector(&listExample);

    return 0;
}

Error:

error: no match for 'operator=' (operand types are 'std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >}' and 'std::basic_string<char>')|
error: no match for 'operator!=' (operand types are 'std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >}' and 'std::basic_string<char>')|

Solution

  • You can just use them as references and make it easy for your self...

    #include <iostream>
    #include <list>
    #include <vector>
    #include <string>
    
    template<class T>
    void convertListToVector(std::list<T> &listItem) {
    typename std::list<T>::iterator it;
    for (it = listItem.begin(); it != listItem.end(); it++)
            std::cout << *it <<std::endl;
    }
    
    int main()
    {
        std::list<std::string> listExample;
        listExample.push_back("2");
        listExample.push_back("3");
        listExample.push_back("5");
        convertListToVector(listExample);
    
        return 0;
    }
    

    Rule Of Thumb

    Use references the whole time. Only pointers when you have to. You may ask why?

    1. Pointers tend to confuse programmers. Even experienced ones.
    2. Pointers can change what they are 'pointing' to. Which can be terrible in some occasions.
    3. Pointers can be null.. For example:

    In C++11:

       int *p1 = nullptr;
    

    Other C++:

       int *p1 = NULL;
       int *p2 = 0;
    
    1. References have to reference an object. Meaning you cant just put a number on a 'reference' of int

    Best Practices

    1: Note that you can't change what references are referencing so just add the keyword const before your references, so they dont change what they are pointing to. It's best practice and also makes sure you don't make a silly mistake as changing what your references are referencing.

      const int x = 0;
      const int &ref = x