【问题标题】:Sending an array between two functions C++在两个函数 C++ 之间发送一个数组
【发布时间】:2014-01-04 23:17:09
【问题描述】:

我试图在 C++ 中的两个函数之间发送一个包含 15 个整数的数组。第一个函数允许用户输入出租车 ID,第二个函数允许用户从数组中删除出租车 ID。但是我在函数之间发送数组时遇到问题。

void startShift ()
{
    int array [15]; //array of 15 declared 

    for (int i = 0; i < 15; i++)
    {
        cout << "Please enter the taxis ID: ";
        cin >> array[i]; //user enters taxi IDs

        if (array[i] == 0)
            break;
    }

    cout << "Enter 0 to return to main menu: ";
    cin >> goBack;
    cout << "\n";
    if (goBack == 0)
        update();
}

void endShift ()
{
    //need the array to be sent to here

    cout << "Enter 0 to return to main menu: ";
    cin >> goBack;
    cout << "\n";
    if (goBack == 0)
        update();
}

任何帮助都非常有价值。非常感谢。

【问题讨论】:

  • 使用C++11和std::array(或std::vector
  • 尝试使用指向数组的指针而不是数组本身。

标签: c++ arrays function


【解决方案1】:

由于数组已在堆栈上创建,您只需将指针作为 int* 传递给第一个元素

void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}

int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}

由于数组是在堆栈上创建的,一旦创建它的例程退出,它将不再存在。

【讨论】:

  • 好的,我有这个工作。当我查看数组列表时,我只得到一个输入的 ID,而且它总是我输入的第二个?
  • 你能发布你正在使用的代码吗? arr[0] 当然是第一个元素,arr[14] 是第十五个元素。
  • void endShift (int* arr) { int val = arr[1, 2, 3]; cout
  • 问题是 (1, 2, 3) 会返回单个 int,而 arr[1,2,3] 会返回单个 int。如果要查看数组的内容,则需要类似 void endShift(int* arr){for (int i = 0; i
【解决方案2】:

在这些函数之外声明数组并通过引用将其传递给它们。

void startShift(int (&shifts)[15]) {
 // ...
}
void endShift(int (&shifts)[15]) {
 // ...
}

int main() {
  int array[15];
  startShift(array);
  endShift(array);
}

这不是完全漂亮的语法或所有常见的。一个更可能的写法是传递一个指向数组的指针和它的长度。

void startShift(int* shifts, size_t len) {
  // work with the pointer
}

int main() {
  int array[15];
  startShift(array, 15);
}

惯用 C++ 将完全不同,并使用迭代器从容器中抽象出来,但我认为这超出了这里的范围。无论如何,这个例子:

template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
  // work with the iterators
}

int main() {
  int array[15];
  startShift(array, array + 15);
}

您也不会使用原始数组,而是使用std::array

【讨论】:

    【解决方案3】:

    startShift() 函数中使用本地数组是行不通的。您最好执行以下一项或多项操作:

    1. 在调用startShift()endShift() 的函数中使用数组并将数组传递给这些函数,例如:

      void startShift(int* array) { ... }
      void endShift(int* array) { ... }
      int main() {
          int arrray[15];
          // ...
          startShift(array);
          // ...
          endShift(array);
          // ...
      }
      
    2. 首先不要使用内置数组:改用std::vector&lt;int&gt;:该类自动维护数组的当前大小。您也可以从函数中返回它,尽管您可能仍然最好将对象传递给函数。

    【讨论】:

      【解决方案4】:
      void endShift (int* arr)
      {
          arr[0] = 5;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        相关资源
        最近更新 更多