如何修改代码以打印出数组 v2
How to modify the code to print out the array v2
我的代码使用 for 循环来复制和粘贴 V1 -> V2 的内容。我想使用 cout 查看 v2 的输出,但我不确定将那行代码放在哪里。
void copy_fct();
int main()
{
copy_fct();
}
void copy_fct()
{
int v1[10] = {0,1,2,3,4,5,6,7,8,9};
int v2[10];
for (int i=0; i!=10; ++i){
v2[i]=v1[i];
}
}
#include <iostream>
void copy_fct();
int main()
{
copy_fct();
}
void copy_fct()
{
int v1[10] = {0,1,2,3,4,5,6,7,8,9};
int v2[10];
for (int i=0; i!=10; ++i){
v2[i]=v1[i];
std::cout << v2[i] << " ";
}
std::cout << std::endl;
}
在程序设计中,函数copy_fct
的名称没有多大意义,因为它不复制用户传递给函数的任何内容。它处理其局部变量。
看来你的意思是这样的。
#include <iostream>
void copy_fct( const int a1[], size_t n, int a2[] )
{
for ( size_t i = 0; i < n; i++ ) a2[i] = a1[i];
}
int main()
{
const size_t N = 10;
int v1[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int v2[N];
copy_fct( v1, N, v2 );
for ( int item : v2 ) std::cout << item << ' ';
std::cout << 'n';
return 0;
}
程序输出为
0 1 2 3 4 5 6 7 8 9
使用标准算法可以完成相同的任务。
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
const size_t N = 10;
int v1[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int v2[N];
std::copy( std::begin( v1 ), std::end( v1 ), std::begin( v2 ) );
std::copy( std::begin( v2 ), std::end( v2 ), std::ostream_iterator<int>( std::cout, " " ) );
return 0;
}
相关文章:
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 在一定长度后从数组中打印时缺少整数
- 数组元素打印的递归方法
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 打印矢量数组中的所有元素
- 打印问题.我在数组中打印值时遇到一些问题
- 数组类 阵列的打印输出
- 动态分配的聊天数组打印缺失的数据和空
- 如何打印 2D 字符数组C++
- 如何修改代码以打印出数组 v2
- 在C++中初始化和打印 2D 数组
- 将浮点数转换为无符号字符数组并打印出来
- C++ 打印包含数据结构的数组
- 如何让字符数组在一行而不是多行中打印出来?
- 打印字符数组地址的正确方法
- 按字母顺序打印存储在字符数组中的信息
- 使用递归反转和打印出数组的内容
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 加载有空指针的字符数组的打印值