A vector of strings

A

amphetaman

Hello. I am writing code to put the traditional C-style command-line
arguments into a std::vector of std::strings. I was wondering: which
is the best way to do it? Are they identical?

#include <string>
#include <vector>

int mymain(const std::vector<std::string> &);

int main(int argc, char *argv[])
{
std::vector<std::string> theArgv;
for (int i = 0; i < argc; i++)
{
// a) or b) ?
}
return mymain(theArgv);
}

a) theArgv.push_back(argv);

b) theArgv.push_back(std::string(argv));

Any help is appreciated. :)
 
K

Kai-Uwe Bux

Hello. I am writing code to put the traditional C-style command-line
arguments into a std::vector of std::strings. I was wondering: which
is the best way to do it? Are they identical?

#include <string>
#include <vector>

int mymain(const std::vector<std::string> &);

int main(int argc, char *argv[])
{
std::vector<std::string> theArgv;
for (int i = 0; i < argc; i++)
{
// a) or b) ?
}
return mymain(theArgv);
}

a) theArgv.push_back(argv);

b) theArgv.push_back(std::string(argv));

Any help is appreciated. :)


What about

c)

int main ( int argn, char ** args ) {
std::vector< std::string > argument ( args, args+argn );



Best

Kai-Uwe Bux
 
A

amphetaman

std::vector< std::string > argument ( args, args+argn );

Could you please explain that line in detail? I don't seem to
understand what it does.
 
K

Kai-Uwe Bux

Could you please explain that line in detail? I don't seem to
understand what it does.

std::vector<T> has a constructor

template < Iterator >
vector ( Iterator from, Iterator to );

This constructor will construct a vector of Ts from any range whose elements
are convertible to T. Since char* converts to std::string, you can
construct a vector of strings from any range of char* Now, args is a
pointer to an array of char*, therefore

[args, args+argn)

is a range of char*.


Best

Kai-Uwe Bux
 
R

Rolf Magnus

Kai-Uwe Bux said:
What about

c)

int main ( int argn, char ** args ) {
std::vector< std::string > argument ( args, args+argn );

Any particular reason for confusing people by calling the parameters of main
argn and args instead of the usual argc and argv?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top