C++ 初始化Vector

C++ 初始化Vector 首页 / C++入门教程 / C++ 初始化Vector

向量可以存储多个数据值(例如数组),但它们只能存储对象引用,而不能存储原始数据类型。它们存储对象的引用,意味着它们指向包含数据的对象,而不是存储它们。与数组不同,向量不必使用大小初始化。它们具有根据对象引用数进行调整的灵活性,这是可能的,因为它们的存储由集合自动处理。集合将保留alloc的内部副本,该副本用于分配生命周期的存储。可以使用迭代器定位和遍历向量,因此将它们放置在连续的存储中。与Array不同,Vector还具有安全函数,可以防止程序崩溃。我们可以给向量保留空间,但不能给数组留空间。数组不是类,而向量是类。在vector中,可以删除元素,但不能删除数组中的元素。

有四种方法可以在C++中初始化向量:

  • 通过一对一输入值
  • 使用向量类的重载构造函数
  • 借助数组
  • 通过使用另一个初始化的向量

通过push_back

使用向量类方法" push_back"可以一个向量地插入向量中的所有元素。

   Begin
   Declare v of vector type.
   Then we call push_back() function. This is done to insert values into vector v.
   Then we print "Vector elements: \n".
  " for (int a: v)
      print all the elements of variable a."

代码-

#include <iostream>
#include <vector>
using namespace std;
int main() 
{
  vector<int> vec;  
  vec.push_back(1); 
  vec.push_back(2); 
  vec.push_back(3);
  vec.push_back(4); 
  vec.push_back(5);
  vec.push_back(6); 
  vec.push_back(7); 
  vec.push_back(8);
  vec.push_back(9); 
  vec.push_back(101);
  for (int i = 0; i < vec.size(); i++)
  {
    cout << vec[i] << " "; 
  }
  return 0; 
}

输出

Initialize Vector in C++

使用重载构造函数-

当一个向量具有多个具有相同值的元素时,则使用此方法。通过使用vector类的重载构造函数-

此方法主要在向量填充具有相同值的多个元素时使用。

算法

Begin
   First, we initialize a variable say 's'.
   Then we have to create a vector say 'v' with size's'.
   Then we initialize vector v1.
   Then initialize v2 by v1.
   Then we print the elements.
End.

代码-

#include <iostream>
#include <vector>
using namespace std;
int main()
 {
  int elements = 12; 
  vector<int> vec(elements, 8); 
  for (int i = 0; i < vec.size(); i++)
  {
    cout << vec[i] << " \n"; 
  }
  return 0; 
}  

输出

8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8

通过数组

我们将数组传递给vector类的构造函数。数组包含将填充矢量的元素。

算法-

Begin
   First, we create a vector say v.
   Then, we initialize the vector.
   In the end, print the elements.
End.

代码-

#include <iostream>
#include <vector>
using namespace std;
int main() 
{
  vector<int> vectr{9,8,7,6,5,4,3,2,1,0}; 
  for (int i = 0; i < vectr.size(); i++)
  {
    cout << vectr[i] << " \n"; 
  }
  return 0;
}

输出

9 
8 
7 
6 
5 
4 
3 
2 
1 
0

使用另一个初始化向量-

在这里,我们必须将初始化向量的begin()和end()迭代器传递给向量类构造函数。然后,我们初始化一个新向量,并用旧向量填充它。

算法-

Begin
   First, we have to create a vector v1.
   Then, we have to initialize vector v1 by an array.
   Then we initialize vector v2 by v1.
   We have to print the elements.
End.

代码-

#include <iostream>
#include <vector>
using namespace std;
int main() 
{
  vector<int> vec_1{1,2,3,4,5,6,7,8};
  vector<int> vec_2(vec_1.begin(), vec_1.end());
  for (int i = 0; i < vec_2.size(); i++)
  {
    cout << vec_2[i] << " \n"; 
  }
  return 0; 
}

输出

1 
2 
3 
4 
5 
6 
7 
8

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

深入浅出区块链 -〔陈浩〕

MySQL实战45讲 -〔林晓斌〕

Swift核心技术与实战 -〔张杰〕

深入浅出云计算 -〔何恺铎〕

说透数字化转型 -〔付晓岩〕

讲好故事 -〔涵柏〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

Rust 语言从入门到实战 -〔唐刚〕

好记忆不如烂笔头。留下您的足迹吧 :)