第九章 顺序容器

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类型不支持复制和赋值运算,所以不可以用容器来存储

Exercise 9.6:

Given a class type named Foo that does not define a default constructor but does define a constructor that takes int values, define a list of Foo that holds 10 elements.

假设有一个名为 Foo 的类,这个类没有定义默认构造函数,但提供了需要一个 int 型参数的构造函数,定义一个存放 Foolist 对象,该对象有 10 个元素。

                              list<Foo> my_Foo(10, 1);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值