Vector <string> or vector <char *>?
Question:
What is the difference between:
vector<string>andvector<char *>?
How to pass a data type:
stringvalue to a function that specifically accepts:const char *?
For instance :
vector<string> args(argv, argv + argc); vector<string>::iterator i; void foo (const char *); //*i - I understand using
vector<char *>: I will need to copy the data as well as the pointer
Edit:
Thanks for entering!
This really has nothing to do with vectors.
A char* is a pointer that may or may not indicate valid string data.
A std::string is a string class that encapsulates all the necessary data that makes up a string, as well as distribution and release functions.
If you store std::string in a vector or in another place, then everything will work.
If you store char pointers, you need to do all the hard work of allocating and freeing memory, and ensure that pointers only point to significant string data and determine the length of strings, etc.
And since char* expected from a large number of C APIs, as well as from part of the C ++ standard library, the string class has a c_str() function that returns char* .
char* is actually a pointer to a value of type char that defines what can and cannot be done with this value. You can make int* number and number reference to a pointer to a memory block where this value is stored, and suppose that it is int and will block this type for this memory block. But you can save char 'C' in this memory block, but it will cause a compilation error because it says that you cannot execute these int functions on this char .
From http://www.cplusplus.com/reference/string/string/ :
String objects are a special type of container specifically designed to work with sequences of characters.
Unlike traditional c-strings, which are simple sequences of characters in an array of memory, C ++ string objects belong to a class with many built-in functions for working with strings in more intuitive and additional useful functions common to C ++ containers.
char* is a pointer to a character, no more.
You can use c_str() to pass the data required as const char* .
As for copying, if you copy the data, you will have a new place for the row and therefore a new pointer.