c ++引用数组

时间:2010-10-16 16:28:19

标签: 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;
}

以下是我的错误:

|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)’|

感谢您的帮助

5 个答案:

答案 0 :(得分:19)

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

void f(int a[])

相当于

void f(int* a)

因此,如果需要进行复制,则不会进行复制。

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

void f(int (&a)[10])

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

答案 1 :(得分: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;
}

答案 2 :(得分:5)

如果将writeTable设为功能模板,则无需指定数组的维度。

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

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

答案 3 :(得分:1)

根据Amardeep的回答,这是一种C ++ 11方法:

#include <iostream>
#include <vector>

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

    for (auto& cell : tab)
    {
        std::cout << "Enter value " << i+1 << std::endl;
        if (std::cin >> val)
        {
            cell = val;
        }
    }
}


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

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

    return 0;
}

请注意for中使用的基于范围的writeTable

答案 4 :(得分:0)

如果您正在尝试这样做,则参考数组是非法的。从标题中我不是100%清楚。