如何typedef嵌套容器的迭代器?

时间:2011-01-27 19:25:31

标签: c++ iterator typedef typetraits

在以下代码中声明迭代器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; 
}

4 个答案:

答案 0 :(得分:3)

以STL方式执行并传递迭代器,而不是容器:

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

答案 1 :(得分:2)

您的容器是const,但您的迭代器类型不是。制作const_iterator

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

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

答案 2 :(得分:1)

尝试使用const迭代器:

typedef typename Mat::value_type::const_iterator itr;

答案 3 :(得分:1)

你传递为const&amp;,所以你need a const_iterator

typedef typename Mat::value_type::const_iterator itr;
itr i = (mat.begin())->begin();