C++的Vector<vector>
的函数及使用
vector
是 C++ 标准库中的一个数组类,提供了动态数组(array)的实现。vector
库提供了以下函数:
函数名 | 函数描述 |
---|---|
vector::push_back(T item) | 将元素 item 添加到 vector 的末尾。 |
vector::pop_back() | 弹出 vector 的末尾元素。 |
vector::back() | 获取 vector 的末尾元素的引用,但不弹出元素。 |
vector::insert(position, T item) | 在 vector 的指定位置插入元素 item 。(填参数需要使用:名称.begin() + n ) |
vector::erase(position) | 删除 vector 的指定位置的元素。(填参数需要使用:名称.begin() + n ) |
vector::size() | 获取 vector 的元素个数。 |
vector::empty() | 判断 vector 是否为空。 |
vector::clear() | 清空 vector 。 |
以下是一个使用 vector
库的例子,它展示了如何创建一个 vector
,向 vector
中添加元素,删除元素,以及判断 vector
是否为空和是否满足容量要求:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::cout << "back: " << v.back() << std::endl;
std::cout << "size: " << v.size() << std::endl;
v.erase(v.begin() + 1);
std::cout << "back: " << v.back() << std::endl;
std::cout << "size: " << v.size() << std::endl;
std::cout << "capacity: " << v.capacity() << std::endl;
std::cout << "is full: " << (v.size() >= v.capacity() ? "yes" : "no") << std::endl;
return 0;
}
在这个例子中,我们使用 std::vector<int>
创建了一个整数类型的 vector
。然后,我们向 vector
中添加了三个元素,并使用 back()
函数获取 vector
的末尾元素的引用。接着,我们使用 size()
函数获取 vector
的元素个数,并使用 erase()
函数删除了 vector
的第二个元素。最后,我们使用 capacity()
函数获取 vector
的容量,并使用 is full
函数判断 vector
是否已满。
以下为示例代码:
#include <iostream>
#include <vector>
using namespace std;
vector<int> arr;//定义arr的vector,<>里面写类型。好处:vector是动态处理,可以增加和删除元素。
void Push_back() //在末尾插入元素
{
int temp;
while (1)
{
cin >> temp;
if (temp != 0)
{
arr.push_back(temp);
}
else break;
}
for (int num : arr)
{
cout << num << " ";
}
}
void Pop_back()//删除末尾元素
{
arr.pop_back();
cout << endl;
for (int num : arr)
cout << num << " ";
}
void Insert()//修改某位置的元素
{
int position = 0, num = 0;
cout << endl << "Position:";
cin >> position;
cout << endl << "Number:";
cin >> num;
arr.insert(arr.begin() + position - 1, num); //必须写作begin()
cout << endl;
for (int num : arr)//循环缩写,遍历所有元素,但不过没有下标
cout << num << " ";
}
void Erase1()//删除某一位置的元素
{
int position;
cout << endl << "Position:";
cin >> position;
arr.erase(arr.begin() + position - 1);//必须写作begin()
cout << endl;
for (int num : arr)
cout << num << " ";
}
void Erase2()//删除某一区间的元素
{
int l, r;
cout << endl << "Position LEFT";
cin >> l;
cout << endl << "Position RIGHT" << endl;
cin >> r;
arr.erase(arr.begin() + l - 1, arr.begin() + r - 1);//必须写作begin()
for (int num : arr)
cout << num << " ";
}
int main()
{
Push_back();
Pop_back();
Insert();
Erase1();
Erase2();
return 0;
}
希望以上内容对您有所帮助!