C++ std::copy 二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18709577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::copy two dimensional array
提问by Matt
Hello I'm trying to use the std::copy() function to copy a two dimensional array. I was wondering if it's possible to do it like so! I keep getting a "Segmentation Fault" but the array is copied correctly. I've tried subtracting a few and adding a few to the end case for the copy function, but with no success.
您好,我正在尝试使用 std::copy() 函数来复制二维数组。我想知道是否有可能这样做!我不断收到“分段错误”,但数组已正确复制。我已经尝试减去一些并在复制功能的最后情况下添加一些,但没有成功。
const int rows = 3;
const int columns = 3;
int myint[rows][columns]={{1,2,3},{4,5,6},{7,8,9}};
int favint[rows][columns];
std::copy(myint, myint+rows*columns,favint);
It's obvious that "myint+rows*columns" is incorrect, and it turns out that this value corresponds to entire rows such that "myint+rows*columns=1" means it will copy the entire first row. if "myint+rows*columns=2" it copies the first two rows etc. Can someone explain the operation of this for me?
很明显,“myint+rows*columns”是不正确的,事实证明这个值对应于整行,这样“myint+rows*columns=1”意味着它将复制整个第一行。如果“myint+rows*columns=2”它复制前两行等。有人可以为我解释这个操作吗?
回答by lulyon
std::copy(myint, myint+rows*columns,favint);
should be:
应该:
std::copy(&myint[0][0], &myint[0][0]+rows*columns,&favint[0][0]);
prototype of std::copy
:
原型std::copy
:
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
Notice that pointer to array element could be wrapper as an iterator.
请注意,指向数组元素的指针可以作为迭代器进行包装。