/************************************************************************/
/* About: STL vector的使用測試 */
/* Author: Clannad */
/* Blog: ............. */
/************************************************************************/
/*
基本操作
1,頭文件包含#<vector>
2,創建vector對象:vector<Point> vec;
3,vector的增刪改查
3.1,vector的添加有兩種方式:
(1)尾部插入vec.pushback(a);
(2)固定位置插入vec.insert(vec.begin() + i,a);在第i+1個元素前插入a
3.2,vector刪除元素
(1)刪除單個元素vec.erase(vec.begin() + 2); 刪除第三個元素
(2)刪除區間內元素vec.erase(vec.begin() + i,vec.begin() + j);刪除區間[i,j-1];區間從0開始
3.3,vector的查詢方法
(1)vec的遍歷
(2)查詢具體的某一個只有用下標或者iter
3.4vector的修改
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point
{
float x;
float y;
};
void print(int i)
{
cout<<i;
}
void printfVec(vector<Point> vec_p)
{
//vec的遍歷方法(最優)
//方式1
for (auto v: vec_p)
{
cout<<"X:"<<v.x<<" Y:"<<v.y<<endl;
}
//方式2
auto end = vec_p.end();
for (auto iter = vec_p.begin();iter != end; iter++)
{
cout<<"X:"<<iter->x<<" Y:"<<iter->y<<endl;
}
//注意::先計算end有好處,因爲不必要每次去重複計算end,vector的end()
//不是常數時間的,所以先緩存下來能提高效率。寫算法的時候儘量使用!=比較迭代器,
//因爲<對於很多非隨機迭代器沒有這個操作符。但是這種方式也寫起來比較繁瑣。
//方式3
vector<int> vec_tmp;
for (int i = 0;i < 10;++i)
{
//vec_tmp.insert(i,1);
vec_tmp.push_back(i);
}
vec_tmp.insert(vec_tmp.begin() +1,100);
// class OutPut
// {
// public:
// void operator() (Point v)
// {
// std::cout<<"X:"<<v.x<<endl;
// }
// }
for_each(vec_tmp.begin(),vec_tmp.end(),print);
}
int main()
{
vector<Point> vec;
//添加測試push_back
for (int i = 0;i < 10;++i)
{
Point p;
p.x = 1 + i;
p.y = 1 + i;
vec.push_back(p);
}
//添加測試insert
Point p2;
p2.x = 100;
p2.y = 100;
vec.insert(vec.begin() +1,p2);
printfVec(vec);
//刪除測試()
vec.erase(vec.begin() + 2);
printfVec(vec);
float tmp;
cin>>tmp;
return 0;
}
STL vector的使用總結
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.