Вопрос

Как правильный способ объявить итератор I в следующем коде?

#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; 
}
Это было полезно?

Решение

Сделайте это по пути и пропускайте итераторы, а не контейнеры:

//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; 
}

Другие советы

Ваш контейнер есть const, но ваш тип итератора нет. Сделать это const_iterator:

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

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

Попробуйте константный итератор:

typedef typename Mat::value_type::const_iterator itr;

Вы проходите как констант, так что вы нужен постоянный:

typedef typename Mat::value_type::const_iterator itr;
itr i = (mat.begin())->begin();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top