9.1 顺序容器的定义
1.While most types can be used as the element type of a container, there are two constraints that element types must meet:
C++ 语言中,大多数类型都可用作容器的元素类型。容器元素类型必须满足以下两个约束:
-
The element type must support assignment.
元素类型必须支持赋值运算。
-
We must be able to copy objects of the element type.
元素类型的对象必须可以复制。
2. 如果容器存储类类型的对象,那么只有当其元素类型提供默认构造函数时,容器才能使用这种构造函数。尽管有一些类没有提供默认构造函数,但大多数类类型都会有。例如,假设类 Foo 没有默认构造函数,但提供了需要一个 int 型形参的构造函数。现在,考虑下面的声明:
vector<Foo> empty; // ok: no need for element default constructor vector<Foo> bad(10); // error: no default constructor for Foo vector<Foo> ok(10, 1); // ok: each element initialized to 1
习题:
Exercise 9.4: | Define a list that holds elements that are deques that hold ints. 定义一个 list 对象来存储 deque 对象里的元素,该 deque 对象存放 int 型元素。 |
list < deque < int> > my_list;
Exercise 9.5: | Why can we not have containers that hold iostream objects? 为什么我们不可以使用容器来存储 iostream 对象? |
IO类型不支持复制和赋值运算,所以不可以用容器来存储