views:

1143

answers:

5

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!

+1  A: 
foo(i->c_str());
+1  A: 

To pass a string to something expecting const char *, use the string's c_str() member, which returns a null-terminated string:

string s = "foobar";

int n = strlen( s.c_str() );
anon
A: 

From http://www.cplusplus.com/reference/string/string/ :

String objects are a special type of container, specifically designed to operate with sequences of characters.

Unlike traditional c-strings, which are mere sequences of characters in a memory array, C++ string objects belong to a class with many built-in features to operate with strings in a more intuitive way and with some additional useful features common to C++ containers.

char* is a pointer to a character, nothing more.

You can use the c_str() to pass data that is required as const char*.

As for copying, if you copy the data you will have a new location for the string, and therefore a new pointer.

Dave Hillier
+15  A: 

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

jalf
@jalf: Thanks a lot
Aaron
VC compiler error: "cannot convert parameter 1 from 'const char to LPCSTR' - function PathFileExistA
Aaron
*i->c_str() //any suggestions?
Aaron
@Atklin: Remove the leading *.
Doug
A: 

I would use vector< string >, only because finding would be value based and not address based. However, vector< char* > would be faster, so each has it's benefits.