1

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

4 回答 4

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; 
}
于 2011-01-27T19:37:21.413 回答
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();
}
于 2011-01-27T19:31:52.113 回答
1

试试 const 迭代器:

typedef typename Mat::value_type::const_iterator itr;
于 2011-01-27T19:32:16.060 回答
1

你作为 const& 传递,所以你需要一个 const_iterator

typedef typename Mat::value_type::const_iterator itr;
itr i = (mat.begin())->begin();
于 2011-01-27T19:33:01.850 回答