简体   繁体   English

将字符串2d数组传递给函数

[英]passing string 2d array to a function

I am passing string 2d array to a function in a following way. 我以下列方式将字符串2d数组传递给函数。 Is it correct or can it be done better ? 它是正确的还是可以做得更好?

#include<iostream>
#include<string>
using namespace std;

void print_name(string name[])
{
    cout<<name[0];
}

int main()
{
    string name[4];
    name[0] = "abc";
    name[1] ="xyz";
    name[2] = "pqr";
    name[3]= "xyq";

    print_name(name);
    return 0;
}

In C++ a better way is to pass a std::vector as the parameter. 在C ++中,更好的方法是传递std::vector作为参数。

void print_name(const std::vector<std::string>& name)

and

std::vector<std::string> name{"abc", "xyz","pqr","xyq"};

print_name(name);

The problem with passing C-style arrays is that the function that you call does not know where it ends. 传递C风格数组的问题在于,您调用的函数不知道它的结束位置。 If you must use a fixed-size array, a better approach would be to pass std::array<std::string,4> : 如果必须使用固定大小的数组,更好的方法是传递std::array<std::string,4>

void print_name(std::array<std::string,4>& names) ...

If using std::vector<std::string> is acceptable, it would give your code more flexibility: 如果使用std::vector<std::string>是可以接受的,那么它将为您的代码提供更大的灵活性:

void print_name(std::vector<std::string>& names) ...

If none of the above works for you, consider passing the number of array items along with the array, so that your print_name knows how may items it gets: 如果以上都不适合您,请考虑将数组项的数量与数组一起传递,以便print_name知道它可以获取的项目:

void print_name(std::string names[], int count) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM