CivDav
CivDav

Reputation: 102

C++ passing array of strings to a function

So I want to pass an array of std::strings to a function. The number of std::strings in the array is predefined via preproc. directives. The whole thing should look like this:

#define ARRAYSIZE 3
void foo(std::string[ARRAYSIZE]);
void foo(std::string instrings[ARRAYSIZE])
{
...
}

Question: Can I call on the function without having to save the std::string array first to a variable, and then calling with that? So basically I want to call it with one line, like:

void main()
{
...
foo( std::string x[ARRAYSIZE] = {"abc","def","ghi"}  );
...
}

Problem is that I can't figure out the correct syntax of the function call (I'm not even sure there is one), visual studio's intellisense keeps shooting my ideas down.

Upvotes: 0

Views: 220

Answers (2)

Maurice
Maurice

Reputation: 610

One way to pass multiple values like this {x0,x1,x2,...} would be to use std::initializer_list which was introduced in c++11. Although this way it is not possible to force a constant number of values.

void foo(const std::initializer_list<std::string>& input) {

}

int main() {
    foo({"abc","def","ghi"});
}

Upvotes: 1

Ilya Kobelevskiy
Ilya Kobelevskiy

Reputation: 5345

If you would like to switch to std::vector that can be constructed on the fly as you have mentioned in the comment to the question, this should work (works with gcc):

void foo(const std::vector<std::string> &stringVec)
{
}

int main()
{
    foo( std::vector<std::string>({"abc","def","ghi"}));
}

Upvotes: 3

Related Questions