Vector <string> or vector <char *>?

Question:

  • What is the difference between:

    • vector<string> and vector<char *> ?
  • How to pass a data type: string value 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!

+4
source share
7 answers

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

+17
source

To pass string to the expected const char * , use the string c_str() member, which returns a string with a terminating zero:

 string s = "foobar"; int n = strlen( s.c_str() ); 
+3
source

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 .

+3
source
 foo(i->c_str()); 
+1
source

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.

+1
source

I would use vector< string > because the search will be based on values, not based on addresses. However, vector< char* > will be faster, so each of them has its own advantages.

+1
source

vector<char *> sounds like a bad idea! If your program does not work in a system with limited memory.

0
source

All Articles