嵌套通用容器迭代 C++
nested generic container iteration C++
我正在自学使用模板,并且一直想知道是否有一种方法可以以通用方式迭代嵌套容器。我见过以这种方式遍历单个容器的示例。
这是一个向量的向量的函数示例。我想让它也适用于 valarrays 的向量和数组的数组,而不必为每个都编写一个单独的函数。提前致谢。
// matrix sum of two vectors of vectors
template<typename T>
vector<vector<T>> sum(vector<vector<T>> const &M1,
vector<vector<T>> const &M2) {
vector<vector<T>> MS(M2.size(), vector<T>(M2[0].size()));
for (unsigned int i = 0; i < MS.size(); ++i) {
for (unsigned int j = 0; j < MS[i].size(); ++j) {
MS[i][j] = M1[i][j] + M2[i][j];
}
}
}
我建议如下(STL 风格):
// matrix sum of two twodimensional containers
template<typename InputIterator, typename OutputIterator>
OutputIterator sum(InputIterator first1, InputIterator last1,
InputIterator first2, OutputIterator result) {
if(first1 == last1) { return result; } // Check for empty container
for (; first1 != last1; ++first1, ++first2) {
std::transform(std::begin(*first1), std::end(*first1),
std::begin(*first2), std::begin(*result),
std::add<void>{});
++result;
// Please be aware that this only works if the result container
// has already the dimensions of the input containers.
// std::back_inserter does not work with this implementation.
}
return result;
}
这种风格的算法应该适用于普通数组、向量、std::arrays 等...
注意:该算法未经测试。
编辑:此算法适用于 c++14。
我正在自学使用模板,并且一直想知道是否有一种方法可以以通用方式迭代嵌套容器。我见过以这种方式遍历单个容器的示例。
这是一个向量的向量的函数示例。我想让它也适用于 valarrays 的向量和数组的数组,而不必为每个都编写一个单独的函数。提前致谢。
// matrix sum of two vectors of vectors
template<typename T>
vector<vector<T>> sum(vector<vector<T>> const &M1,
vector<vector<T>> const &M2) {
vector<vector<T>> MS(M2.size(), vector<T>(M2[0].size()));
for (unsigned int i = 0; i < MS.size(); ++i) {
for (unsigned int j = 0; j < MS[i].size(); ++j) {
MS[i][j] = M1[i][j] + M2[i][j];
}
}
}
我建议如下(STL 风格):
// matrix sum of two twodimensional containers
template<typename InputIterator, typename OutputIterator>
OutputIterator sum(InputIterator first1, InputIterator last1,
InputIterator first2, OutputIterator result) {
if(first1 == last1) { return result; } // Check for empty container
for (; first1 != last1; ++first1, ++first2) {
std::transform(std::begin(*first1), std::end(*first1),
std::begin(*first2), std::begin(*result),
std::add<void>{});
++result;
// Please be aware that this only works if the result container
// has already the dimensions of the input containers.
// std::back_inserter does not work with this implementation.
}
return result;
}
这种风格的算法应该适用于普通数组、向量、std::arrays 等...
注意:该算法未经测试。 编辑:此算法适用于 c++14。