简体   繁体   中英

Convert const std::vector<std::string> to const char **

I have a function with signature like this:

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

I want convert vector args to const char ** (just like argv in main). How this can be done? We can't actually make a char ** array because then it (obviously) fails to convert args[i].c_str() that is of type const char * to char * .

The only (ugly) way I can think of is to use const_cast to cast from const char * to char * .

Would anyone suggest more elegant way of doing this? I should note I can use only c++03 features.

Thanks in advance.

It can't be done without an extra array. A const char** means "a pointer to a pointer to const char" - so you need a place where there are actual pointers to char to point to.

So you need to create that array.

struct c_str { const char* operator ()(const std::string& s) { return s.c_str(); } };
std::vector<const char*> pointers(args.size());
std::transform(args.begin(), args.end(), pointers.begin(), c_str());
// If you really want to be compatible with argv:
pointers.push_back(0);
// &pointers[0] is what you want now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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