如何在c ++中复制数组

时间:2017-09-02 17:30:25

标签: c++ arrays

我试图在函数doSomething中捕获数组实例,因为c ++中的数组是通过引用传递的,这是不可能的。是否有解决此问题的解决方法!

#include <iostream>
using namespace std;
int *A[10][10];

void doSomething(int ar[],int n){
    A[1][2] = ar;
    for (int i=0;i<n;i++){
        ar[i]+=1;
    }
    A[2][3] = ar;
}


int main(){
    int ar[] = {1,2,3,4,5};
    int n = 5;
    doSomething(ar,n);
    for (int i=0;i<n;i++){
        cout<<A[1][2][i]<<" "; // this should be 1 2 3 4 5 but output is 2 3 4 5 6 
    }
    cout<<endl;
    for (int i=0;i<n;i++){
        cout<<A[2][3][i]<<" ";
    }

}

这里第一个cout在main将打印2 3 4 5 6但是在这里我要输出为1 2 3 4 5

2 个答案:

答案 0 :(得分:1)

使用std::array<std::array<std::array<int, 5>, 10>, 10>或使用Boost的专用类型:

#include <boost/multi_array.hpp>

int main() {
    boost::multi_array<int, 3> A(boost::extents[10][10][5]);
}

<强> Live On Coliru

#include <boost/multi_array.hpp>
#include <algorithm>
#include <iostream>

using Array3d = boost::multi_array<int, 3>;
using Ref     = boost::const_multi_array_ref<int, 1>;
Array3d A{boost::extents[10][10][5]};

void doSomething(Ref const& ar) {
    A[1][2] = ar;
    A[2][3] = ar;
    for (auto& el : A[2][3]) el += 1;
}

template <typename Sub>
void dump(std::ostream& os, Sub const& ar) {
    std::copy(std::begin(ar), std::end(ar), std::ostream_iterator<int>(os, " "));
}

int main(){
    int ar[] {1,2,3,4,5};
    doSomething(Ref{ar, boost::extents[5]});

    dump(std::cout << "\nA[1][2] = ", A[1][2]);
    dump(std::cout << "\nA[2][3] = ", A[2][3]);
}

打印

A[1][2] = 1 2 3 4 5 
A[2][3] = 2 3 4 5 6 

我想对于这个简单的案例你可以用std::vector<int> A[10][10]做。甚至是std::array<int, 5> A[10][10]

<强> Live On Coliru

#include <array>
#include <algorithm>
#include <iterator>
#include <iostream>

using Array5 = std::array<int, 5>;
Array5 A[10][10] {};

void doSomething(Array5 const& ar) {
    A[1][2] = ar;
    A[2][3] = ar;
    for (auto& el : A[2][3]) el += 1;
}

void dump(std::ostream& os, Array5 const& ar) {
    std::copy(std::begin(ar), std::end(ar), std::ostream_iterator<int>(os, " "));
}

int main(){
    doSomething({{1,2,3,4,5}});

    dump(std::cout << "\nA[1][2] = ", A[1][2]);
    dump(std::cout << "\nA[2][3] = ", A[2][3]);
}

答案 1 :(得分:-1)

不要使用糟糕的C阵列 - 它们毫无价值。请改用std :: array / std :: vector。