首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将新数组分配给引用变量

将新数组分配给引用变量
EN

Stack Overflow用户
提问于 2022-05-07 15:16:50
回答 3查看 76关注 0票数 -1
代码语言:javascript
复制
void byReference(int (&p)[3]){
    int q[3] = {8, 9, 10};
    p = q;
}

我想编写函数,在那里我可以用新数组重新分配p。我不确定我们是否能做到。

我的目标:我想改变原来的数组,就像我们通过调用通过引用交换两个数字一样。

编辑:

我的工作解决方案:

代码语言:javascript
复制
void byReference(int*& p){
    int* q = new int[2];
    q[0] = 8;
    q[1] = 9;
    
    p = q;
}

int main(){
    int *x = new int[2];
    x[0] = 1;
    x[1] = 2;

    byReference(x);
    
    return 0;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-05-07 15:32:43

在c++中,建议对固定大小数组使用std::array,对动态大小数组使用std::vector

它们都可以通过引用传递,由函数修改。这要求函数声明该参数是通过引用使用&符号传递的。

参见下面的示例:

代码语言:javascript
复制
#include <array>
#include <vector>

// Get an array (with a fixed size of 3) by refernce and modify it:
void ModifyStdArray(std::array<int, 3> & a) {
    a = std::array<int, 3>{8, 9, 10};
    // or:
    a[0] = 8;
    a[1] = 9;
    // etc.
}

// Get a vector by refernce and modify it:
void ModifyStdVector(std::vector<int> & v) {
    v = std::vector<int>{ 1,2,3,4 };
    // or:
    v.clear();
    v.push_back(1);
    v.push_back(2);
    // etc.
}

int main()
{
    std::array<int, 3> a1;
    // Pass a1 by reference:
    ModifyStdArray(a1);
    // Here a1 will be modified.

    std::vector<int> v1;
    // Pass v1 by reference:
    ModifyStdVector(v1);
    // Here v1 will be modified.
}
票数 0
EN

Stack Overflow用户

发布于 2022-05-07 15:38:08

你可以这样做:

代码语言:javascript
复制
#include <iostream>
#include <array>
#include <algorithm>

// with std::array
void byReference( std::array<int, 3>& p )
{
    const std::array<int, 3> q { 8, 9, 10 };
    std::copy_n( std::begin( q ), std::size( p ), std::begin( p ) ); // copy q to p
}

// with C-style arrays
void byReference( int (&p)[ 3 ] )
{
    const int q[ 3 ] { 8, 9, 10 };
    std::copy_n( std::begin( q ), std::size( p ), std::begin( p ) ); // copy q to p
}


int main( )
{
    std::array<int, 3> arr;
    // int arr[ 3 ]; // or this one

    byReference( arr );

    std::cout << "The array is: ";
    std::copy_n( std::begin( arr ), std::size( arr ),
                 std::ostream_iterator<int>( std::cout, " " ) ); // copy the elements of arr to
                                                                 // the stdout (aka print them)
    std::cout << '\n';
}

输出:

代码语言:javascript
复制
The array is: 8 9 10 
票数 0
EN

Stack Overflow用户

发布于 2022-05-07 15:38:53

不能通过赋值复制数组。您可以使用std::copy

代码语言:javascript
复制
void byReference(int(&p)[3]) {
    int q[3] = { 8, 9, 10 };
  //  p = q;
    std::copy(&q[0], &q[3], &p[0]);
}

……

代码语言:javascript
复制
int a[3] = { 1, 2, 3 };
byReference(a);

// a now 8,9,10
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72153819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档