C++ Vector的基本使用

C++ Vector的基本使用

#include <iostream>
#include <vector>

using namespace std;

//刪除
template<typename T>
void vectorDelete(int nIndex, vector<T>& vDatas)
{
	std::vector<T>::iterator it = vDatas.begin() + nIndex;
	vDatas.erase(it);
}

//顯示 模板顯示 只能適用與普通類型;
template<typename T>
void vectorShow(vector<T>& vDatas)
{
	vector<T>::iterator pos;
	for (pos = vDatas.begin(); pos != vDatas.end(); pos++)
	{
		cout << *pos << "\t";
	}
	cout << endl;
}

int main()
{
	cout << "Vector 的使用" << endl;

	//1.創建;  int 可以是結構體 或者 類;
	vector<int> vIntDatas;

	//2.添加;
	vIntDatas.push_back(10);
	vIntDatas.push_back(8);
	vIntDatas.push_back(6);
	vIntDatas.push_back(4);
	vIntDatas.push_back(2);

	//3.遍歷;
	vector<int>::iterator pos;
	for (pos = vIntDatas.begin(); pos != vIntDatas.end(); pos++)
	{
		cout << *pos << "\t";
	}
	cout << endl;

	//4.刪除; 
	cout << "刪除 索引 1的數據" << endl;
	vectorDelete<int>(1, vIntDatas);
	vectorShow<int>(vIntDatas);

	//5.修改;
	cout << "修改索引 0 數據" << endl;
	vIntDatas[0] = 100;
	vectorShow<int>(vIntDatas);
	
	//6.交換;
	cout << "交換 索引[0]-索引[3]的數據" << endl;
	swap(vIntDatas[0], vIntDatas[3]);
	vectorShow<int>(vIntDatas);

	//7.釋放;
	vector<int>().swap(vIntDatas);

	system("Pause");
	return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章