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>')|
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;
}
Use references the whole time. Only pointers when you have to. You may ask why?
In C++11:
int *p1 = nullptr;
Other C++:
int *p1 = NULL;
int *p2 = 0;
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