设为首页 加入收藏

TOP

3.3 Library vector Type (2)
2013-10-07 16:18:54 来源: 作者: 【 】 浏览:80
Tags:3.3 Library vector Type

3.3.1 Defining and Initializing vectors

As with any class type, the vector template controls how we define and initialize vectors. Table 3.4 (p. 99) lists the most common ways to define vectors.

We can default initialize a vector (§ 2.2.1, p. 44), which creates an empty vector of the specified type:

  1. vector<string> svec; // default initialization; svec has no elements  

It might seem that an empty vector would be of little use. However, as we’ll see shortly, we can (efficiently) add elements to a vector at run time. Indeed, the most common way of using vectors is to define an initially empty vector to which elements are added as their values become known at run time. We can also supply initial value(s) for the element(s)when we define a vector. For example, we can copy elements from another vector. When we copy a vector, each element in the new vector is a copy of the corresponding element in the original vector. The two vectors must be the same type:

  1. vector<int> ivec; // initially empty   
  2. // give ivec some values   
  3. vector<int> ivec2(ivec); // copy elements of ivec into ivec2   
  4. vector<int> ivec3 = ivec; // copy elements of ivec into ivec3   
  5. vector<string> svec(ivec2); // error: svec holds strings, not ints 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.3 Library vector Type (1) 下一篇第6条:当心 C++编译器最烦人的分..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 Python 进行数据 (2025-12-25 15:49:09)
·如何学习Python数据 (2025-12-25 15:49:07)
·利用Python进行数据 (2025-12-25 15:49:04)
·Java 学习线路图是怎 (2025-12-25 15:19:15)
·关于 Java 学习,有 (2025-12-25 15:19:12)