C ++-是否可以在不指定类型的情况下实例化“ vector”?

Ely*_*Ely 5 c++ stl vector

非常基本,但是很难在Google中为我搜索。

我正在在线上进行C ++培训课程,主题是STL。在这种情况下vector

是否可以在vector不指定类型的情况下实例化a ?

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector v1(10, 0);
    cout<<"Size: "<<v1.size()<<endl;
    for(unsigned i = 0; i < v1.size(); ++i)
    {
        cout<< v1[i]<<" ";
    }
    cout<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为这是错误的,但是我在整个课程中都看到了这一点,这使我感到困惑。

使用时vector<int> v1(10, 0)它会编译,这就是我的想法。

在使用NetBeans的过程中,但我认为没有配置或参数或任何可以实现该目标的东西,是吗?

MSC*_*MSC 7

C++17 确实支持无类型向量的实例化。请看这篇文章,https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

想要查询更多的信息。

因此,例如编写此代码将起作用:

vector v {1, 2, 3};  // instead of vector<int>
Run Code Online (Sandbox Code Playgroud)

如果您使用此“-std=c++17”标志进行编译。


Jer*_*fin 5

一般模板

std::vector暂时忽略细节,可以为类模板的模板参数定义默认类型。例如:

template <class T = int>
class foo { 
    T *bar;
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不必指定类型来实例化该模板。同时,您必须包含模板参数列表。诀窍在于该列表可以为空,因此您可以通过以下任一方式实例化该模板:

foo<long> a; // instantiate over long. The `int` default is just ignored
foo<int>  b; // instantiate over int. Still doesn't use default
foo<>     c; // also instantiates over int
Run Code Online (Sandbox Code Playgroud)

std::vector具体来说

std::vector确实使用分配器类型的默认参数,但不为存储的类型提供默认值,因此定义如下所示:

template <class T, class allocator = std::allocator<T>>
class vector
// ...
Run Code Online (Sandbox Code Playgroud)

因此,如果您没有另外指定,向量的分配器类型将std::allocator在您存储的相同类型上进行实例化 - 但您始终必须指定您要存储的类型,因为没有提供默认值对于那种类型。

概括

绝对可以为模板的所有参数指定默认值,在这种情况下,可以在实例化时不(显式)指定类型来实例化模板 - 但std::vector有一个模板参数没有提供默认值,因此instantiate 时vector,您必须指定该参数的类型。