6.16 An introduction to std::vector

原完整教程链接:6.16 An introduction to std::vector

In the previous lesson, we introduced std::array, which provides the functionality of C++’s built-in fixed arrays in a safer and more usable form.

Analogously, the C++ standard library provides functionality that makes working with dynamic arrays safer and easier. This functionality is named std::vector.

Unlike std::array, which closely follows the basic functionality of fixed arrays, std::vector comes with some additional tricks up its sleeves. These help make std::vector one of the most useful and versatile tools to have in your C++ toolkit.

1.Declaring a std::vector is simple:

#include <vector>
 
// no need to specify length at initialization
std::vector<int> array; 
std::vector<int> array2 = { 9, 7, 5, 3, 1 }; // use initializer list to initialize array
std::vector<int> array3 { 9, 7, 5, 3, 1 }; // use uniform initialization to initialize array (C++11 onward)

2.As of C++11, you can also assign values to a std::vector using an initializer-list:

array = { 0, 1, 2, 3, 4 }; // okay, array length is now 5
array = { 9, 8, 7 }; // okay, array length is now 3

3.Vectors remember their length

Unlike built-in dynamic arrays, which don’t know the length of the array they are pointing to, std::vector keeps track of its length. We can ask for the vector’s length via the size() function:

#include <vector>
#include <iostream>
 
int main()
{
    std::vector<int> array { 9, 7, 5, 3, 1 };
    std::cout << "The length is: " << array.size() << '\n';
 
    return 0;
}

4.Resizing an array

Resizing a built-in dynamically allocated array is complicated. Resizing a std::vector is as simple as calling the resize() function:

(1)

#include <vector>
#include <iostream>
 
int main()
{
    std::vector<int> array { 0, 1, 2 };
    array.resize(5); // set size to 5
 
    std::cout << "The length is: " << array.size() << '\n';
 
    for (auto const &element: array)
        std::cout << element << ' ';
 
    return 0;
}

This prints:

The length is: 5
0 1 2 0 0

(2)

#include <vector>
#include <iostream>
 
int main()
{
    std::vector<int> array { 0, 1, 2, 3, 4 };
    array.resize(3); // set length to 3
 
    std::cout << "The length is: " << array.size() << '\n';
 
    for (auto const &element: array)
        std::cout << element << ' ';
 
    return 0;
}

This prints:

The length is: 3
0 1 2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,447评论 0 23
  • 1、概括力 古典文学有很强的概括力,比如,《红楼梦》的金陵十二钗,每位都有一首判词,总结概括一生。 判词:钗黛合一...
    风里雨里我等你阅读 1,085评论 0 1
  • 2016年接近尾声,倒数时间。回首这过去的一年,自己在成长也在失去。抓住的也松手了,握紧的也成为过去;喜欢的依然没...
    亦清的碎碎念阅读 3,126评论 0 0
  • 终于从过年的散漫里收回,早起拜日,双盘, 一大早送完穗儿上幼儿园,到公司居然还空无一人。 当你等的门未开时,索性停...
    沄间一杯茶阅读 1,735评论 0 0
  • 校区:科学创想机器人和平校区 时间:周六10:40-11:40 学员:杜沈轩,杜辽轩 任教老师:杨玲 教学目标: ...
    Happy00阅读 1,443评论 0 0