mardi 31 mai 2016

How to iterate over a generic vector

I've always found C++ templates inscrutable, and C++ error messages more so. I want to understand it, rather than always feeling confused. Here's the latest bizarre experience:

error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’ requested

This doozy comes from the following code:

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
void printVector(const vector<T>& v) {
    for (typename vector<T>::iterator iter = v.begin; iter != v.end; iter++) {
        cout << *iter << endl;
    }
}

int main() {
    vector<int> v{1, 2, 3};
    printVector(v);
    return 0;
}

It has no problem iterating over the vector if I use a C++11 range-based loop. I want to learn how to do it using iterators.

Can someone explain what the error means and how to fix it?

It would also be wonderful if I could get a recommendation of a book that explains templates well.

Aucun commentaire:

Enregistrer un commentaire