Question:
What is the difference between:
vector<string>
and vector<char *>
?How would I pass a value of data type: string
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
vector<char *>
: I'll have to copy the data, as well as the pointerThanks for input!
These are interchangeable, std::string just offers additional functionality.
TLDR: string s are optimized to only contain character primitives, vector s can contain primitives or objects. The preeminent difference between vector and string is that vector can correctly contain objects, string works only on primitives.
std::string offers a very different and much expanded interface compared to std::vector<> . While the latter is just a boring old sequence of elements, the former is actually designed to represent a string and therefore offers an assortment of string-related convenience functions.
From a purely philosophical point of view: yes, a string is a type of vector. It is a contiguous memory block that stores characters (a vector is a contiguous memory block that stores objects of arbitrary types). So, from this perspective, a string is a special kind of vector.
This really has nothing to do with vectors specifically.
A char*
is a pointer, which may or may not point to valid string data.
A std::string
is a string class, encapsulating all the required data that makes up a string, along with allocation and deallocation functionality.
If you store std::string
's in a vector, or anywhere else, then everything will just work.
If you store char pointers, you have to do all the hard work of allocating and freeing memory, and ensuring the pointers only ever point to meaningful string data, and determine the length of the strings and so on.
And since char*
's are expected by a lot of C API's as well as part of the C++ standard library, the string
class has the c_str()
function which returns a char*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With