I'm learning about vectors in Accelerated C++
by Andrew Koenig and Barbara Moo. Can anyone explain the difference between these?
vector<string> x;
and
vector<string> x(const string& s) { ... }
Does the second one define a function x
whose return type must be a vector and whose return value is stored somehow in x?
The exact code from the book starts like this:
map<string, vector<int> > xref(istream& in, vector<string> find_words(const string&) = split) {
vector<string> x;
This is a declaration of a variable named x
of type vector<string>
vector<string> x(const string& s) { ... }
this is a function named x
that takes 1 parameter of type const string&
and returns a vector<string>
As you can see they are different beasts.
It seems this function definition
map<string, vector<int> > xref(istream& in,
vector<string> find_words(const string&) = split)
{
//...
}
confuses you.
The second parameter has the function type vector<string>(const string&)
that is supplied with the default argument split
.
Take into account that instead of the function type you could use a function pointer type. In any case the compiler adjusts a parameter that has a function type to a parameter that has a function pointer type.
Consider this demonstrative program. The both function declarations declare the same one function. In the first function declaration there is used a function type for the second parameter while in the second function declaration there is used a function pointer type for the same parameter.
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<string> split( const string & );
map<string, vector<int> > xref( istream& in,
vector<string> find_words(const string&) = split );
map<string, vector<int> > xref( istream& in,
vector<string> ( *find_words )(const string&) );
int main()
{
return 0;
}
I only declared the function split
without providing its definition because it is not required for this simple demonstrative program.
So you can call the function xref
either with one argument and in this case the function will use the funcion split
as the second argument by default. Or you could explicitly specify the second argument setting it to the name of your own written function.
You are correct in that the latter is a function. The vector
that function x
creates however is not stored in a variable named x
, rather the function itself is named x
. You might do something like:
string my_str = "Hello world.";
// Call x to create my_vector:
vector<string> my_vector = x(my_str);