Question

What is the proper way to declare the iterator i in the following code?

#include <iostream>
#include <vector>

using namespace std;

template<class Mat> 
void f(const Mat& mat) 
{
    typedef typename Mat::value_type::iterator itr;
    //itr i = (mat.begin())->begin(); //This Line Gives an error
    typeof((mat.begin())->begin()) i = (mat.begin())->begin(); 
}

int main() 
{
    vector<vector<int> > vvi;
    f(vvi);
    return 0; 
}
Was it helpful?

Solution

Do it the STL way and pass iterators, not containers:

//Beware, brain-compiled code ahead!
template<typename It> 
void f(It begin, It end) 
{
    typedef typename std::iterator_traits<It>::value_type cont;
    typedef typename cont::const_iterator const_iterator; // note the const_ pfx
    const_iterator i = begin->begin();
    // ...
}

int main() 
{
    vector<vector<int> > vvi;
    f(vvi.begin(), vvi.end());
    return 0; 
}

OTHER TIPS

Your container is const, but your iterator type is not. Make that const_iterator:

template<class Mat> 
void f(const Mat& mat) 
{
    typedef typename Mat::value_type::const_iterator itr;

    itr i = mat.begin()->begin();
}

Try the const iterator:

typedef typename Mat::value_type::const_iterator itr;

You pass as a const&, so you need a const_iterator:

typedef typename Mat::value_type::const_iterator itr;
itr i = (mat.begin())->begin();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top