如果您的多维向量是一个实际的多维向量,例如 std::vector<std::vector<int>>,不建议这样做,那么您将不得不编写自己的迭代器。这不是很复杂。 Boost.Iterator 有一些概念可以用来帮助实现它。
如果您的多维向量是单个向量,其大小设置为维度的乘积(即宽度 * 高度),这是处理此问题的首选方法,那么它会容易得多。可以使用 Boost.Range 提供的实用程序来完成。
这是一个使用 Boost.Range 的快速而肮脏的例子。使用decltype 可以让它更漂亮一点。如果您的编译器不支持 C++11(特别是 auto),我不建议使用它,因为代码变得非常难以阅读。
template<typename T>
boost::iterator_range<typename T::iterator>
GetRow(T& vec, typename T::size_type row, typename T::size_type w,
typename T::size_type h) {
return boost::make_iterator_range(
vec.begin() + (row * w),
vec.begin() + ((row + 1) * w)
);
}
template<typename T>
boost::strided_range<boost::iterator_range<typename T::iterator>>
GetColumn(T& vec, typename T::size_type col, typename T::size_type w,
typename T::size_type h) {
boost::iterator_range<typename T::iterator> range = boost::make_iterator_range(
vec.begin() + col,
vec.begin() + col + (h - 1) * w + 1
);
return boost::strided_range<boost::iterator_range<typename T::iterator>>(w, range);
}
然后使用这些函数非常容易,但如果你的编译器不支持auto,它会变得非常难看。
const size_t WIDTH = 3;
const size_t HEIGHT = 3;
std::vector<int> vec(WIDTH * HEIGHT);
// Fill the first row with 1.
auto row = GetRow(vec, 0, WIDTH, HEIGHT);
for (auto it = row.begin(); it != row.end(); ++it) {
(*it) = 1;
}
// Fill the second column with 2.
auto col = GetColumn(vec, 1, WIDTH, HEIGHT);
for (auto it = col.begin(); it != col.end(); ++it) {
(*it) = 2;
}
// Contents of vec is:
// 1 2 1
// 0 2 0
// 0 2 0
您可能还想研究 Boost.MultiArray,这是一个用于此类事情的库。它提供了你想要的功能,但它绝对不是最友好的库。