簡體   English   中英

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

[英]How to typedef the iterator of a nested container?

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

使用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; 
}

您的容器是const ,但您的迭代器類型不是。 使該const_iterator

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

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

嘗試使用const迭代器:

typedef typename Mat::value_type::const_iterator itr;

您以const&的身份傳遞,因此需要const_iterator

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM