【问题标题】:Building iteration function of vector's vector in template class在模板类中构建向量向量的迭代函数
【发布时间】:2016-02-18 19:36:04
【问题描述】:

我目前正在编写模板矩阵。 矩阵有一个

vector<vector<T>> names mat, and contains the vectors size (rows and cols).

如何构建一个迭代向量向量的 const 函数?

注意:我需要构建一个

typedef typename std::vector<T>::const_iterator const_iterator

我问的是如何构建迭代器函数,而不是如何使用迭代器。

到目前为止,这就是我所拥有的:

typedef typename std::vector<T>::const_iterator const_iterator;

const_iterator end()
{
    return mat[rowsNum][colsNum];
}

const_iterator begin()
{
    return mat[0][0];
}

之前尝试过: typedef typename std::vector::const_iterator const_iterator;

const_iterator end()
{
    return mat.end;
}

const_iterator begin()
{
    return mat.begin;
}

-- 编辑-- 目前,我的代码如下所示:

template<class T>
class Matrix
{
private:
...
public:
...
    typedef typename std::vector<T>::const_iterator const_iterator;

    const_iterator end()
    {
        return mat[rowsNum][colsNum];
    }

    const_iterator begin()
    {
        return mat[0][0];
    }
}
}

就是这样。 有问题吗?

【问题讨论】:

  • 呸。锯齿状边缘“矩阵”的另一种实现方式,其内存被分配到各处。每次我看到这些东西之一,我都会在内心深处死去。

标签: c++ vector iterator


【解决方案1】:

你有向量的向量,所以,你的迭代器应该是

typedef typename std::vector<std::vector<T>>::const_iterator const_iterator;

函数应该是

const_iterator end() const
{
    return mat.end();
}

const_iterator begin() const
{
    return mat.begin();
}

【讨论】:

  • 无法转换 '((const Matrix*)this)->Matrix::mat.std::vector<_tp _alloc>::begin<:vector std::allocator> >, std::allocator<:vector std::allocator> > > >()' from 'std::vector<:vector std::allocator> >, std::allocator<:vector std::allocator> > >::const_iterator {aka __gnu_cxx::__normal_iterator >*, std::vector<:vector std::allocator> >, std::allocator<:vector std::allocator> > > > >}'
  • to 'Matrix::const_iterator {aka __gnu_cxx::__normal_iterator > >}' return mat.begin ();
  • @COOKIE 你在我的帖子中使用了正确的 typedef,是吗?这样,应该没问题。
  • 执行此操作:无法将 'std::basic_ostream' 左值绑定到 'std::basic_ostream&&'
  • @COOKIE 这是另一个问题,另一个问题。您发布的代码中没有运算符
【解决方案2】:

避免使用std::vector&lt;std::vector&lt;T&gt;&gt;。它在内存中不连续,效率不高,从中处理迭代器并不简单。

我建议您,因为您似乎想使用 Matrix 容器来展平您的数组并使用线性 std::vector&lt;T&gt; 代替,这样您就必须重复使用 std::vector&lt;T&gt;::const_iterator

示例

 template<class T>
 struct Matrix {
    using const_iterator = std::vector<T>::const_iterator;
    std::vector<T> mat;
    size_t rows;
    size_t cols;

    // [...] constructors etc...

    const_iterator end() const {
        return mat.end();
    }

    const_iterator begin() const {
        return mat.begin();
    }
    // and you don't need to specify anything else for your iterators.

    const T& operator()(size_t i, size_t j) const { return mat[i * rows + j]; } // depends if row major or column major storage
    // [...] and other convenient methods...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2011-08-05
    相关资源
    最近更新 更多