📜  C++ STL中Vector的默认值

📅  最后修改于: 2021-05-30 09:37:00             🧑  作者: Mango

向量与动态数组相同,具有在插入或删除元素时自动调整自身大小的能力,并且容器自动处理其存储。向量元素放置在连续的存储中,以便可以使用迭代器对其进行访问和遍历。默认情况下,附加元素时向量的大小会自动更改。

使用以下随机默认值初始化地图的方法是:
方法:

  1. 声明一个向量。
  2. 将向量的大小设置为用户定义的大小N

向量的默认值:

向量的默认值为0

句法:

// For declaring 
vector v1(size); 

// For Vector with default value 0
vector v1(5);

下面是上述方法的实现:

// C++ program to create an empty
// vector with default value
  
#include 
using namespace std;
  
int main()
{
    int n = 3;
  
    // Create a vector of size n with
    // all values as 0.
    vector vect(n);
  
    for (int x : vect)
        cout << x << " ";
  
    return 0;
}
输出:
0 0 0

指定向量的默认值:

我们还可以为向量指定一个随机默认值。为了做到这一点,下面是方法:

句法:

// For declaring 
vector v(size, default_value);

// For Vector with a specific default value
// here 5 is the size of the vector
// and  10 is the default value
vector v1(5, 10);

下面是上述方法的实现:

// C++ program to create an empty vector
// and with a specific default value
  
#include 
using namespace std;
  
int main()
{
    int n = 3;
    int default_value = 10;
  
    // Create a vector of size n with
    // all values as 10.
    vector vect(n, default_value);
  
    for (int x : vect)
        cout << x << " ";
  
    return 0;
}
输出:
10 10 10
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”