如何修改代码打印出数组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];

    }

}

在您的程序设计中,函数名称 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;
}
#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;

}