C++ 程序:使用 STL 初始化向量(第一部分)

原文:https://www.studytonight.com/cpp-programs/cpp-program-initialising-a-vector-in-stl-part-1

大家好!

在本教程中,我们将学习用 C++ 编程语言初始化向量的各种方法。

什么是向量?

向量与动态数组相同,能够在插入或删除元素时自动调整自身大小。这使得它们比固定大小且本质上是静态的普通数组更有优势。

要了解更多关于 CPP 中的向量,我们将推荐您访问 STL 向量容器

为了更好地理解,请参考下面给出的注释良好的 C++ 代码。

代号:

#include<iostream>
#include<bits/stdc++.h>

using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate the various ways of Initializing a Vector (Part 1), in CPP  ===== \n\n";

    cout << "Method 1: Using push_back() method\n\n";

    //create an empty vector
    vector<int> v;

    //insert elements into the vector
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    //prining the vector
    cout << "The elements of the first vector are: ";

    for (int i : v)
    {
        cout << i << " ";
    }

    cout << "\n\n\n\n\nMethod 2: Initializing all the elements with a specific value\n\n";

    //creating a vector of size 5 with all values initalized to 10
    vector<int> v1(5, 10);

  //prining the vector
    cout << "The elements of the second vector are: ";
     for (int i : v1)
    {
        cout << i << " ";
    }

    cout << "\n\n\n";

    return 0;
}

输出:

C++ Vector Initialization

我们希望这篇文章能帮助你更好地理解向量的概念及其在 C++ 中的实现。如有任何疑问,请随时通过下面的评论区联系我们。

继续学习: