什么是 vector<int,int> 它甚至有效吗?

What is vector<int,int> Is it even valid?

我一直在使用 vector < pair < int,int>>,但我不知道像 vector< int,int> 这样的东西也存在,我可以声明它, 但是不知道怎么用

vector < int,int>是一个有效的容器吗,如果是的话那有什么区别 和 vector < pair < int,int>> ?

如果不能,为什么我可以申报?

What is vector<int,int>

std::vector的第二个tempalate参数是allocator,所以这是一个vector,其allocator的类型是int.

Is it even valid?

没有。 int 不满足分配器的要求。

if no, why am I able to declare it??

嗯,用至少两个模板参数实例化一个模板,最多两个没有默认值的模板参数使用两个类型参数是 well-formed。直到您尝试使用分配器,您才可能遇到 well-formedness.

问题

模板参数必须满足特定属性的语言无法表达,标准库也没有这样的规定。提议在未来的 C++ 标准中引入的 Concepts 功能可用于强制执行(某些)此类要求,并且将来可能还会要求容器使用 concepts。

如果您的模板实例化不符合标准容器的要求规范,标准不要求编译器诊断错误。引用最新标准草案:

[res.on.functions]

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, this document places no requirements on the implementation.

In particular, the effects are undefined in the following cases:

  • for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause ([allocator.requirements], [container.requirements], [iterator.requirements], [algorithms.requirements], [numeric.requirements]). Operations on such types can report a failure by throwing an exception unless otherwise specified.

声明理论上可以编译,因为没有限制。在我的系统上,它无法编译。

这里的关键是std::vector

中的模板参数列表

根据文档@https://devdocs.io/cpp/header/vectorstd::vector 有两个模板参数,T(要存储的东西的类型)和一个 Allocator,这是一些匹配 Allocator 概念的类型。

template <class T, class Allocator = allocator<T> >
class vector

分配器用于进行分配。如果您传递一个 int 作为分配器,它应该无法编译(这对我来说确实如此),因为 int 不包含 Allocator.

中预期的任何功能

您的第一个示例,vector<pair<int, int>> 是一个向量,其中包含的对象是一对整数,使用的 Allocator 是默认值。