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

时间:2015-07-17 16:25:57

标签: c++ vector stl

如此基本,但很难在Google中为我搜索。

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

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

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

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

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

在我们使用NetBeans的过程中,我不认为有配置或参数或任何可以实现这一点的内容,是吗?

6 个答案:

答案 0 :(得分:3)

不,std::vector是一个模板,如果不指定模板参数,则无法实例化。

答案 1 :(得分:3)

您必须指定类型,因为它不是从构造函数的参数推断出来的。但是,没有人禁止你这样做

std::vector<int> make_vector(std::vector<int>::size_type n, int val)
{
      return std::vector<int>(n, val);
}

// ...
auto v2 = make_vector(10, 0);

为什么无法做到这一点,请查看this问题和相关问题。

答案 2 :(得分:3)

可以(使用不同的设置):

#include <vector>
#include <iostream>

using std::cout;
using std::endl;
using vector = std::vector<int>;

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

注意,使用&#39;使用&#39;小心。

答案 3 :(得分:3)

一般的模板

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

template <class T = int>
class foo { 
    T *bar;
};

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

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

std::vector具体

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

template <class T, class allocator = std::allocator<T>>
class vector
// ...

所以,如果你没有另外指定,那么向量的分配器类型将是std::allocator实例化的,与您存储的类型相同 - 但是你做< / em>总是必须指定您要存储的类型,因为没有为该类型提供默认值。

摘要

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

答案 4 :(得分:1)

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

了解更多信息。

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

Private Sub Limpar_Click()
Dim iShp As InlineShape
For Each iShp In ActiveDocument.InlineShapes
  If iShp.OLEFormat.ClassType = "Forms.CheckBox.1" Then
                iShp.OLEFormat.Object.Value = False
            End If
    Next
End Sub

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

答案 5 :(得分:0)

除了它是语法错误之外,没有类型的向量在逻辑上是没有意义的。你要的是一个列表,但是没有列表......你究竟打算将它打印出来的是什么?