C++ Vector初始化
Vector 可以存储多个数据值(例如数组),但它们只能存储对象引用,而不能存储原始数据类型。它们存储对象的引用,意味着它们指向包含数据的对象,而不是存储它们。与数组不同, Vector 不必使用大小初始化。它们具有根据对象引用数进行调整的灵活性,这是可能的,因为它们的存储由容器自动处理。容器将保留alloc的内部副本,该副本用于分配生命周期的存储。可以使用迭代器定位和遍历 Vector ,因此将它们放置在连续的存储中。与Array不同,Vector还具有安全功能,可以防止程序崩溃。我们可以给 Vector 保留空间,但不能给数组留空间。数组不是类,而 Vector 是类。在 Vector 中,可以删除元素,但不能删除数组中的元素。
对于父级 Set 类", Vector 以模板类的形式发送。数组是具有特定属性的低级数据结构。 Vector 具有函数和构造函数;它们不是基于索引的。它们与数组相反,后者是基于索引的数据结构。这里,最低地址提供给第一个元素,最高地址提供给last元素。 Vector 用于插入和删除对象,而数组用于频繁访问对象。数组是节省内存的数据结构,而Vector利用更多的内存进行交换来管理存储并动态增长。 Vector 需要花费更多的时间来访问元素,但是使用数组不是这种情况。
有四种初始化 C++中的 Vector :
通过一对一输入值
使用 Vector 类的重载构造函数
借助数组
通过使用另一个初始化的 Vector
通过一对一输入值-
可以使用 Vector 类方法'push_back来一次插入 Vector 中的所有元素。"
算法
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;
}
输出
使用重载的构造函数-
当 Vector 具有多个具有相同值的元素时,我们将使用此方法。
通过使用vector类的重载构造函数-
此方法主要在 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;
}
输出
借助数组-
我们将数组传递给 Vector 类的构造函数。数组包含将填充 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;
}
输出
在这里,我们使用另一个初始化 Vector -
在这里,我们必须将初始化 Vector 的begin()和end()迭代器传递给 Vector 类构造函数。然后,我们初始化一个新 Vector ,并用旧 Vector 填充它。
算法-
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;
}
输出