我们如何在 c++ 中将字符串数组传递给另一个函数,以及如何访问被调用函数中的每个字符串
How do we pass array of strings to another function in c++ and how do we access each string in the called function
通过引用将字符串数组传递给另一个函数时,如何逐个打印被调用函数中的值(字符串),以及需要在被调用函数的输入参数中声明的参数类型是什么。
您可以通过引用传递数组,如下所示:
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";
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 使用用户定义函数的字符串反转
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 在c++构造函数中使用随机字符串生成器
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- C++:如何使函数只返回作为列表一部分的字符串
- 如何在C++中的同一函数中使用字符串和双精度
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 对函数 PlaySound 使用字符串变量
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 构造函数字符串参数未设置窗口标题
- C++默认构造函数:字符串参数与字符串参数()
- 使用函数C++字符串输入
- c++模板函数字符串类型不匹配