【问题标题】:How to typedef the iterator of a nested container?如何 typedef 嵌套容器的迭代器?
【发布时间】:2011-01-27 19:25:31
【问题描述】:

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

【问题讨论】:

  • 不使用 const 是错误的。我无法从错误行中理解这一点。

标签: c++ iterator typedef typetraits


【解决方案1】:

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

【讨论】:

  • cont:: 命名空间从何而来?
  • @fabrizioM: typedef typename std::iterator_traits&lt;It&gt;::value_type cont;
【解决方案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();
}

【讨论】:

    【解决方案3】:

    试试 const 迭代器:

    typedef typename Mat::value_type::const_iterator itr;
    

    【讨论】:

      【解决方案4】:

      你作为 const& 传递,所以你 need a const_iterator:

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

      【讨论】:

        猜你喜欢
        • 2011-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 2012-12-28
        相关资源
        最近更新 更多