我们如何在 c++ 中将字符串数组传递给另一个函数,以及如何访问被调用函数中的每个字符串

How do we pass array of strings to another function in c++ and how do we access each string in the called function

本文关键字:函数 字符串 访问 何访问 调用 另一个 数组 c++ 我们      更新时间:2023-10-16

通过引用将字符串数组传递给另一个函数时,如何逐个打印被调用函数中的值(字符串),以及需要在被调用函数的输入参数中声明的参数类型是什么。

您可以通过引用传递数组,如下所示:

template <int N>
void foo(string (&arr)[N])
{
  arr[0] = "a";
  arr[1] = "b";
  /// Do other stuff with arr
}

现在,您可以像使用常规数组一样简单地使用arr。需要N模板参数是大小i和大小j的数组,在i!=j时是不同的类型。

这里有一种方法:

void Func(const std::string* stringArr, int arraySize) {
  for ( int n = 0; n < arraySize; ++n ) {
     const std::string& sz = stringArr[n];
  }
}

std::string array[10];
Func(array, 10); // here array decays to pointer to its first element
#include <iostream>
using namespace std;
string getConcatenate(string arr[], int size)
{
    string concatenate;
    for (int i = 0; i < size; ++i)
    {
        concatenate += arr[i];
        if (i != size - 1)
            concatenate += " ";
    }
    return concatenate;
}
int main()
{
    string balance[6] = { "This", "is", "an", "example", "string", "array" };
    string sentence;
    sentence = getConcatenate(balance, 6);
    cout << "Concatenated value is: " << sentence.c_str() << endl;
    getchar();
    return 0;
}

此示例说明,将字符串作为数组发送并返回字符串。

void output_function(string str[])

并使用 str 作为普通数组。

如果你在

如何定义"字符串数组"方面有一定的灵活性,我建议你使用标准容器。

如果你的"数组"是固定大小的,请使用std::array,否则使用std::vector

void doSomethingWithAnArray(const std::array<std::string, 5>& strings);
void doSomethingWithAVector(const std::vector<std::string>& strings);

然后,访问容器中每个字符串的一种方法是使用基于范围的 for 循环。例如:

for (auto& str : strings)
    std::cout << str << " ";
std::cout << "n";