如何修改代码以打印出数组 v2

How to modify the code to print out the array v2

本文关键字:打印 数组 v2 代码 何修改 修改      更新时间:2023-10-16

我的代码使用 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;
}