Vector操作練習

2021-10-24 14:17:41 字數 3024 閱讀 3065

//#include "stdafx.h"

#include#include#include#includeusing namespace std;

int main()

; for (auto i = k.begin(); i != k.end(); ++i)

std::cout << *i << endl;

for (auto e : k)

cout << e ;

cout for (int i = 0; i<10; ++i)

for (auto e : ba)

cout << e;

cout <<"ba" //定義具有10個整型元素的向量(尖括號為元素型別名,

//它可以是任何合法的資料型別),不具有初值,其值不確定

vectorarray(10,10);

//定義具有10個整型元素的向量,且給出的每個元素初值為1

//vectora(10, 1);

//用向量b給向量a賦值,a的值完全等價於b的值

//vectora(b);

vectorarray1(array);

for (auto abc : array1)

cout << abc;

cout << endl;

for (int i = 0; i<10; ++i)

for (auto abcd : array1)

cout << abcd;

cout << endl;

將向量b中從0-2(共三個)的元素賦值給a,a的型別為int型

//vectora(b.begin(), b.begin + 3);

vectorfuzhi(array1.begin(),array1.end()-1);

for (int i=0; i!=fuzhi.size();++i)

cout << fuzhi[i];

cout << endl;

int b[8] = ;

vector***(b,b+7);

for (int i = 0; i != ***.size(); ++i)

cout << ***[i];

//從陣列中獲得初值

//int b[7] = ;

//vectora(b, b + 7);

cout << endl;

//bool ddd = k.clear();

// assign 賦值函式

vectorv(10, 0);

double amd[10] = ;

v.assign(amd, amd + 5);

for (auto nvida : v)

cout << nvida;

cout << endl;

if(***.empty())

for (auto nvida1 : v)

cout << nvida1;

cout << endl;

v.pop_back();

該函式不接受乙個引數

刪除第乙個元素 其餘元素向前排列

for (auto nvida2 : v)

cout << nvida2;

cout << endl;

v.erase(v.begin()+ 1, v.begin() + 2);//刪除指定位置 指定個數的元素

//這個比較有用 niubi

for (auto nvida2 : v)

cout << nvida2;

cout << endl;

cout << v.size();

cout << endl;

//cout << v.capacity();

v.resize(10,2);

v.reserve(100);

/*for (auto nvida3 : v)

cout << nvida3;*/

for (int i = 0; i < v.size(); i++)

cout << v[i];

cout << endl;

cout << v.back();

cout << endl;

cout << v.front();

cout << endl;

//插入操作

v.insert(v.begin() + 2, 9);

v.push_back(8);

cout <= v) << endl;

cout << (ba <= v) << endl;

cout << (ba != v) << endl;

int aa[15] = ;

vectorab;

vectorabc(aa,aa+5);

vectorabcd1(aa + 8, aa + 14);

vectorabcd2(aa, aa + 7);

for (vector::iterator it = abc.begin(); it < abc.end(); it++)

for (int i = 0; i < ab.size(); i++)

cout << ab[i];

cout << "ab" << endl;

cout << endl;

abcd1.swap(abcd2);//swap 只能交換 資料型別相同的vector向量

for (int i = 0; i < abcd1.size(); ++i)

cout << abcd1[i];

cout << ":-1" << endl;

for (int i = 0; i < abcd2.size(); i++)

cout << abcd2[i];

cout << ":-2" << endl;

return 0;

//下面為迭代器方式讀取操作

//int a[6] = ;

//vectorb(a, a + 4);

//for (vector::iterator it = b.begin(); it != b.end(); it++) }

vector操作整理

其迭代器函式原型 iterator begin const iterator begin const iterator end const iterator end const reverse iterator rbegin const reverse iterator rbegin const r...

vector操作小結

前面了解了一下vector,現在我們來看看vector的相關操作。int main vectorv5 vectorv6 3 只提供數量而略去初始值,int 0,string 空串 vector iterator it push back向vector物件中新增元素 for int i 0 i 10 ...

vector 清空操作

size vector容器真實大小,對應resize調整size大小,增加的元素為預設值。capacity 預分配的記憶體空間,對應reserve調整capacity大小。只是調整capacity大小,記憶體還是野的,如果用 進行訪問,可能出現陣列越界。include includeusing na...