如何使用的算法,以填补载体的载体 [英] How to use algorithms to fill vector of vectors
问题描述
我
typedef std::vector<int> IVec;
typedef std::vector<IVec> IMat;
和我想知道我可以填写一个 IMAT
通过使用std算法,即如何做到少code以下(所有 IVEC
取值具有相同的大小)?
and I would like to know how I can fill an IMat
by using std algorithms, ie how to do the following with less code (all the IVec
s have the same size) ?
void fill(IMat& mat){
for (int i=0;i<mat.size();i++){
for (int j=0;j<mat[i].size();j++){
mat[i][j] = i*j;
}
}
}
PS:已经是一个方式来填补的矩阵与一个常数,就帮我。而preferably用pre-C ++ 11的算法。
PS: already a way to fill the matrix with a constant would help me. And preferably with pre-C++11 algorithms.
推荐答案
最好的解决办法是,你已经实现了的。这需要使用优势我
/ Ĵ
既偏移和作为输入来计算的算法。
The best solution is the one that you have already implemented. It takes advantage of using i
/j
as both offsets and as inputs to compute the algorithm.
标准算法将不得不使用迭代器的元素的和的保持计数器。此数据镜像是一个问题的明确信号。不过,这是可以做到,即使是在同一行,如果你想成为奇特的:
Standard algorithms will have to use iterators for the elements and maintain counters. This data mirroring as a sure sign of a problem. But it can be done, even on one line if you wanna be fancy:
for_each(mat.begin(), mat.end(), [&](auto& i) { static auto row = 0; auto column = 0; generate(i.begin(), i.end(), [&]() { return row * column++; }); ++row; });
但由于规定刚刚引起它可以做并不意味着它应该做的。接近这一点的最好办法是在为
-loop。即使是做一行是可能的,如果那是你的事:
But as stated just cause it could be done doesn't mean that it should be done. The best way to approach this is the for
-loop. Even doing it on one line is possible if that's your thing:
for(auto i = 0U;i < mat.size();i++) for(auto j = 0U;j < mat[i].size();j++) mat[i][j] = i*j;
顺便说一下我的标准算法工作正常铛3.7.0 ,的 GCC 5.1 和基于Visual Studio 2015年不过的 previously我用转换
,而不是生成
。而且似乎有一些<一href="http://stackoverflow.com/questions/33285103/capturing-a-lambdas-static-in-a-nested-lambda">implementation在GCC 5.1和Visual Studio 2015年与拉姆达范围静态
变量。
Incidentally my standard algorithm works fine on Clang 3.7.0, gcc 5.1, and on Visual Studio 2015. However previously I used transform
rather than generate
. And there seem to be some implementation bugs in gcc 5.1 and Visual Studio 2015 with the captures of lambda scope static
variables.
这篇关于如何使用的算法,以填补载体的载体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!