向量之间的差异<string> x;和向量<string> x(const string& s) {}

Difference between vector<string> x; and vector<string> x(const string& s) {}

我在 Andrew Koenig 和 Barbara Moo 的 Accelerated C++ 中学习向量。谁能解释一下它们之间的区别?

vector<string> x;

vector<string> x(const string& s) { ... }

第二个是否定义了一个函数 x 其 return 类型必须是向量并且其 return 值以某种方式存储在 x 中?

书中的确切代码是这样开头的:

map<string, vector<int> > xref(istream& in, vector<string> find_words(const string&) = split) {

你说得对,后者是一个函数。然而,函数 x 创建的 vector 并未存储在名为 x 的变量中,而是函数本身被命名为 x。你可以这样做:

string my_str = "Hello world.";
// Call x to create my_vector:
vector<string> my_vector = x(my_str);
vector<string> x;

这是 x 类型 vector<string>

变量的声明
vector<string> x(const string& s) { ... }

这是一个名为 x 的函数,它接受 1 个类型为 const string& 和 returns 的参数 vector<string>

如您所见,它们是不同的野兽。

好像是这个函数定义

map<string, vector<int> > xref(istream& in, 
                               vector<string> find_words(const string&) = split) 
{
    //...
}

让你感到困惑。

第二个参数的函数类型 vector<string>(const string&) 随默认参数 split 一起提供。

请注意,您可以使用函数指针类型代替函数类型。在任何情况下,编译器都会将具有函数类型的参数调整为具有函数指针类型的参数。

考虑这个演示程序。两个函数声明都声明了同一个函数。在第一个函数声明中,第二个参数使用了函数类型,而在第二个函数声明中,同一参数使用了函数指针类型。

#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;
}

我只声明了函数 split 而没有提供它的定义,因为这个简单的演示程序不需要它。

因此您可以使用一个参数调用函数 xref,在这种情况下,该函数将默认使用函数 split 作为第二个参数。或者您可以显式指定第二个参数,将其设置为您自己编写的函数的名称。