C++ const char with .begin() and .end()

1.9k Views Asked by At

So I have a program that looks something like this:

const char *Argv[] = {"stuff", "stuff1", "stuff3"};

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);

I think this is illegal because const char * is not a user-defined type. However, I am not sure how to fix this. Would I need to change the first line or the second? Or both?

2

There are 2 best solutions below

0
leslie.yao On

Argv is an array (of const char*s), and yes you can't call begin() and end() as your code showed, array doesn't have such member functions. Instead, you can use std::begin and std::end for it.

const char *Argv[] = {"stuff", "stuff1", "stuff3"};
bool pass = xxxxx::yyyyy(std::begin(Argv), std::end(Argv), Tri);

If you use other standard containers like std::vector or std::array instead, then you can call the member functions begin() and end() on them. Note that even for these containers you can still use std::begin and std::end on them, which have the same effect as calling their member function begin() and end().

11
cigien On

Just for completeness, and to show the c++ way, you could change the first line to:

std::array<std::string_view, 3> Argv {"stuff", "stuff1", "stuff3"};

and then the second line:

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);

will work just fine.