Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector<string> or vector<char *>?

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
  • I understand using vector<char *>: I'll have to copy the data, as well as the pointer

Edit:

Thanks for input!

like image 211
Aaron Avatar asked Feb 15 '09 00:02

Aaron


People also ask

Is vector of char same as string?

These are interchangeable, std::string just offers additional functionality.

What is the difference between string and vector?

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.

What is the difference between std::string and std :: vector?

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.

Is a string a vector?

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.


1 Answers

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*.

like image 120
jalf Avatar answered Oct 15 '22 12:10

jalf