473,242 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,242 software developers and data experts.

best way to copy a vector<string> to char**

What is the "best" way to copy a vector of strings to an array of
character strings? By "best", I mean most elegantly/tersely written,
but without any sacrifice in performance.

I'm writing an application using C++ and the STL for handling my data.
Unfortunately, I must interact with a (vanilla) C API. I use vectors of
strings (for simplicity and less memory hassle), but the function calls
for this API require arrays of character strings (char**).

Below is some code to copy a vector of strings to an array of character
strings. It works (based on minimal testing anyway :). I'm just
curious if there is a "better" way to do it.

Thanks,
Matt
email at: http://raw-sewage.net/index.php?file=email
// this code is public domain
// compiles with the GNU C++ compiler (g++) v3.2.3

#include <string>
#include <vector>
#include <iostream>
#include <cstring>

using namespace std;

int main(int argc, char** argv)
{
// handy typedefs just to save some typing
typedef std::vector<std::string> strvec_t;
typedef std::vector<std::string>::iterator strveciter_t;

strvec_t strvec;

// fill the string vector with some sample strings
strvec.push_back("Hello"); strvec.push_back(", ");
strvec.push_back("world"); strvec.push_back("... ");
strvec.push_back("How "); strvec.push_back("are ");
strvec.push_back("you "); strvec.push_back("today");
strvec.push_back("?");

// print out the strings (just for sanity)
for (strveciter_t ii=strvec.begin(); ii!=strvec.end(); ++ii)
cout << *ii;
cout << endl;

// allocate memory for an array of character strings
char** cstr = new char*[strvec.size()];

// for each string, allocate memory in the character array and copy
for (unsigned long i=0; i<strvec.size(); i++) {
cstr[i] = new char[strvec[i].size()+1];
strncpy(cstr[i], strvec[i].c_str(), strvec[i].size());
}

// print out the newly copied strings
for (unsigned long i=0; i<strvec.size(); i++) cout << cstr[i];
cout << endl;

// free dynamic memory
for (unsigned long i=0; i<strvec.size(); i++) delete[] cstr[i];
delete[] cstr;

return 0;
}

Jul 22 '05 #1
1 17803
Matt Garman wrote:
What is the "best" way to copy a vector of strings to an array of
character strings? By "best", I mean most elegantly/tersely written,
but without any sacrifice in performance.

I'm writing an application using C++ and the STL for handling my data.
Unfortunately, I must interact with a (vanilla) C API. I use vectors of
strings (for simplicity and less memory hassle), but the function calls
for this API require arrays of character strings (char**).

Below is some code to copy a vector of strings to an array of character
strings. It works (based on minimal testing anyway :). I'm just
curious if there is a "better" way to do it.


Here is another version with a helper class that does what you did but
in a little less.

This version does not allocate anything with new - instead it just uses
the c_str() value as the "char *" which I took the liberty to change to
const char *. Anyhow - if that does not work for you, there is nothing
stopping you from "new"ing whatever you want and deleting it in the
constuctor.

This is a (poor) demonstration of the "low threshold to create a new
class" rule.
// this code is public domain
// compiles with the GNU C++ compiler (g++) v3.2.3

#include <string>
#include <vector>
#include <iostream>
#include <cstring>

using namespace std;

class VectCharPP
{
public:

vector<const char*> ptrs;

VectCharPP( const vector< string > & v )
: ptrs( v.size() + 1 )
{
long i= v.size();

ptrs[ i ] = 0;

for ( --i ; i >= 0; --i ) {
ptrs[ i ] = v[ i ].c_str();
}
}

operator const char ** ()
{
return & ( ptrs[ 0 ] );
}

};
int main(int argc, char** argv)
{
// handy typedefs just to save some typing
typedef std::vector<std::string> strvec_t;
typedef std::vector<std::string>::iterator strveciter_t;

strvec_t strvec;

// fill the string vector with some sample strings
strvec.push_back("Hello"); strvec.push_back(", ");
strvec.push_back("world"); strvec.push_back("... ");
strvec.push_back("How "); strvec.push_back("are ");
strvec.push_back("you "); strvec.push_back("today");
strvec.push_back("?");

// print out the strings (just for sanity)
for (strveciter_t ii=strvec.begin(); ii!=strvec.end(); ++ii)
cout << *ii;
cout << endl;

// allocate new vector here.
VectCharPP cstr_v = strvec;

const char** cstr = cstr_v;

// NOTE THAT cstr only lives as long as the VectCharPP object ...
// since this is a legacy interface we assume this policy is easy
// easy to adhere to.

// print out the newly copied strings
for (unsigned long i=0; cstr[i]; i++) cout << cstr[i];
cout << endl;

return 0;
}

Jul 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: dalbosco | last post by:
Hello, I am new to STL and I've written the following code which crash. Could anyone tell me why this code crash? Thanks by advance. -- J-F #include <iostream>
4
by: misirion | last post by:
Ciao, vorrei poter scrivere e leggere su files binari dei vettori di stringhe, ed avrei implementato questo codice: ifstream fin(conf.c_str(),ios::binary); char inc; fin.read( inc,...
2
by: ehui928 | last post by:
hi, everybody I am a newbie in STL. When I compile the following program under gcc4.0, I got a the following errors. I wonder whether the form of list< vector<string> > is correct in STL ? //...
5
by: Gary Wessle | last post by:
whats an efficient way to copy a string to a vector<string>? how about this? #include <iostream> #include <string> #include <vector> Using namespace std;
10
by: Shafik | last post by:
Hello, I am new to C++. I know the reason is probably template instantiation problems ... but what's the *real* reason I cannot declare a: vector<stringv = vector<string>(4); Thanks!...
2
by: Rockair | last post by:
hi! there is a class: class card { static vector<string> names; //... };
5
by: Etrex | last post by:
Hello, This is my first attempt at a c++ program, and it is a long post, please bear with me. I'm trying to read in a text file containing a firewall log, make the information...
5
by: Peithon | last post by:
Hi, I'm trying to create a vector of strings and print the contents using an iterator but I'm getting an error with my very first string. Can anyone help?
6
by: Mr. K.V.B.L. | last post by:
I want to start a map with keys but an empty vector<string>. Not sure what the syntax is here. Something like: map<string, vector<string MapVector; MapVector.insert(make_pair("string1",...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.