c ++引用数组

Joh*_*ohn 7 c++ arrays reference pass-by-reference

我怎么能让这段代码工作?

#include <iostream>
using namespace std;

void writeTable(int (&tab)[],int x){
    for(int i=0;i<x;i++){
        cout << "Enter value " << i+1 <<endl;
        cin >> tab[i] ;
    }
}


int main(void){
    int howMany;
    cout << "How many elemets" << endl;
    cin >> howMany;

    int table[howMany];
    int (&ref)[howMany]=table;
    writeTable(ref,howMany);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下是我的错误:

|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|
Run Code Online (Sandbox Code Playgroud)

感谢帮助

Arm*_*yan 19

如果您打算传递数组的大小,则删除引用

void f(int a[])
Run Code Online (Sandbox Code Playgroud)

相当于

void f(int* a)
Run Code Online (Sandbox Code Playgroud)

所以如果关注的话,不会进行复制.

如果你想通过引用获取数组,那么你必须指定维度.例如

void f(int (&a)[10])
Run Code Online (Sandbox Code Playgroud)

当然,两者中最好的是第三种解决方案,即使用std :: vector并通过引用传递它们,如果需要,引用const或值.HTH


Ama*_*9MF 6

这是一个稍微更多的C++风格:

#include <iostream>
#include <vector>

void writeTable(std::vector<int> &tab)
{
    int val;

    for (unsigned int i=0; i<tab.size(); i++)
    {
        std::cout << "Enter value " << i+1 << std::endl;
        if (std::cin >> val)
        {
            tab[i] = val;
        }
    }
}


int main()
{
    int howMany;
    std::cout << "How many elements?" << std::endl;
    std::cin >> howMany;

    std::vector<int> table(howMany);
    writeTable(table);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*rav 5

如果创建writeTable函数模板,则无需指定数组的维度.

template <typename T,size_t N>
void writeTable(T (&tab)[N]) //Template argument deduction
{
    for(int i=0 ; i<N ; i++){
       // code ....
    }
}
Run Code Online (Sandbox Code Playgroud)

.

int table[howMany]; // C++ doesn't have Variable Length Arrays. `howMany` must be a constant
writeTable(table);  // type and size of `table` is automatically deduced
Run Code Online (Sandbox Code Playgroud)

  • @Armen:是的!为什么他还需要一个动态分配的数组(他会使用`std :: vector`)? (2认同)