return array of string in function c++
To return an array of strings from a function in C++, you can follow these steps:
- Define the function with the return type as an array of strings. You can use the
std::array
orstd::vector
container classes to represent the array. For example, to usestd::array
, you can declare the function as follows:
cpp
std::array<std::string, N> functionName()
Here, N
represents the size of the array.
- Create an array of strings inside the function. You can use the
std::array
orstd::vector
constructors to initialize the array with the desired strings. For example, to create an array of three strings, you can use the following code:
cpp
std::array<std::string, 3> myArray = { "string1", "string2", "string3" };
Alternatively, you can create an empty array and populate it with strings using the push_back
or emplace_back
functions of std::vector
. For example:
cpp
std::vector<std::string> myArray;
myArray.push_back("string1");
myArray.push_back("string2");
myArray.push_back("string3");
- Return the array from the function. If you are using
std::array
, you can simply use thereturn
statement followed by the array name. If you are usingstd::vector
, you can return it by value. For example:
cpp
return myArray;
- In the calling code, you can capture the returned array by assigning it to a variable of the same type. For example:
cpp
std::array<std::string, 3> result = functionName();
or
cpp
std::vector<std::string> result = functionName();
Now, the result
variable will hold the array of strings returned from the function.
That's it! You have successfully returned an array of strings from a function in C++.