【发布时间】:2014-12-19 12:34:39
【问题描述】:
我正在尝试按行和列遍历自定义矩阵,并使用迭代器来遍历数据。
我在主文件中有一个工作代码,但我发现很难将其转换为 Matrix 类,因为我似乎无法确定 boost::begin 迭代器的返回类型/命令。这是工作代码:
#include <iostream>
#include <algorithm> //std::transform
#include "Matrix.h" //Matrix class
#include <boost/range/algorithm.hpp> //boost::begin, boost::end
#include <boost/range/adaptor/strided.hpp> //boost::adaptor::strided
#include <boost/range/adaptor/sliced.hpp> //boost adaptor::slice
int main(int argc, char *argv[]){
//creats a matrix with 5 rows and 3 colunms filled with ints from 0 to 14
//stores the data internaly as a std::vector<T>
Matrix<int, 5, 3> a = Matrix<int,5,3>(range<int>(15));
//Matrix is accordingly overloaded, prints out the matrix
std::cout << a << std::endl;
//returns an iterator to the second element and then traverses the vector by skipping 5 elments
auto begin = boost::begin(boost::adaptors::stride(
boost::adaptors::slice(a.as_vector(), 1, 15), 5));
//returns an iterator to the end of the vector
auto end = boost::begin(boost::adaptors::stride(
boost::adaptors::slice(a.as_vector(), 1, 15), 5));
//multiplies the second column times 2
std::transform(begin, end, begin,
[](int i) { return 2*i;});
//print result
std::cout << a << std::endl;
}
运行程序返回:
$ ./main
[0,] 0 1 2
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[0,] 0 2 2
[1,] 3 8 5
[2,] 6 14 8
[3,] 9 20 11
[4,] 12 26 14
正如我们所见,它有效。然而,矩阵类中开始/结束的实现导致了问题,特别是因为我需要将“auto”替换为,嗯,我真的不知道是什么。
class Matrix{
//private data members
//contuctors, functions
//returns an iterator to the first element of vector
typename std::vector<T>::iterator Begin(){
return matrix.Begin();
}
typename std::vector<T>::iterator End(){
return matrix.End();
}
//@ matrix: std::vector<T> that holds that data
//@ fun - size(): returns the number of values stored in the matrix
//@ fun - rows(): returns the number of rows of the matrix
//@ param - i: column to iterate through
typename ...return type in question... begin_col( std::size_t i ){
return boost::begin(boost::adaptors::stride(
boost::adaptors::slice( matrix, i, size() ), rows() ) );
}
typename ...return type in question... end_col( std::size_t i ){
return boost::end(boost::adaptors::stride(
boost::adaptors::slice( matrix, i, size() ), rows() ) );
}
//many more overloaded operators and functions
//end of class
};
所以我希望 begin_col() 和 end_col() 的行为方式与两个 std::vector::iterator 几乎相同,仅适用于跨步切片。
矩阵类的其余部分可以在这里找到stackoverflow.com/questions/26282847/c-implementing-iterators-for-custom-matrix-class
最后编译代码: g++ -Wall -O3 -std=c++11 -o main main.cpp Matrix.cpp
在 ubuntu 14.04 上。
非常感谢任何 cmets。
谢谢
文森特
【问题讨论】: