?? chapter6-24.cpp
字號:
//文件名:CHAPTER6-24.cpp
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
void pause() //程序暫停
{ char c;
cout << "\n\nPress return to continue: ";
cin.get(c);
cout << "\n\n";
}
int main()
{
vector<int> v(10,0); //定義一個vector變量,大小為10,值都為0
ostream_iterator<int> out(cout, " "); //定義一個輸出迭代器
copy(v.begin(), v.end(), out);// 通過算法函數copy輸出v中全部的數據
pause(); //程序輸出為:0 0 0 0 0 0 0 0 0 0
vector<int>::iterator i = v.begin(); //定義頭迭代器
i += 4; //指向第5個元素
*i++ = 7; // or v[4] = 7; //使第5個元素值為7,同時迭代器指向下一個元素
*i = 9; // or v[5] = 9; //賦值第6個元素大小為9
copy(v.begin(), v.end(), out); // 把通過迭代器賦值后的所有元素打印出來
pause();//程序輸出為: 0 0 0 0 7 9 0 0 0 0
vector<int>::iterator where = find(v.begin(), v.end(), 9);//在v中查找值為9的元素,并返回相應的迭代器
copy(where, v.end(), out);// 把查找到的元素及其該元素后的數據全部顯示出來。
pause();//程序輸出為:9 0 0 0 0
where = v.insert(where, 8); //在迭代器指示的元素前插入一個元素,其值為8
copy(v.begin(), v.end(), out); //檢驗insert函數的效果
pause();//程序輸出為:0 0 0 0 7 8 9 0 0 0 0
where += 3; //迭代器指示當前元素后的第三個元素為當前元素
where = v.insert(where, 4); //在當前元素前插入一個元素,值為4
copy(v.begin(), v.end(), out);
pause();//程序輸出為:0 0 0 0 7 8 9 0 4 0 0 0
where -= 6;//迭代器前移6個元素
where = v.insert(where, 11); //插入元素11到vector中
copy(v.begin(), v.end(), out);
pause();//程序輸出為:0 0 11 0 0 7 8 9 0 4 0 0 0
v.erase(where+2); // 刪除迭代器后的第2個元素
copy(v.begin(), v.end(), out);
pause();//程序輸出為:0 0 11 0 7 8 9 0 4 0 0 0
sort(v.begin(), v.end()); //對vector進行由大到小排序
copy(v.begin(), v.end(), out);
pause();//程序輸出為:0 0 0 0 0 0 0 4 7 8 9 11
if (binary_search(v.begin(), v.end(), 8)) // vector的查找
cout << "Yes, 8 occurs in vector v.";
else
cout << "No, didn't find 8 in vector v.";
pause();//程序輸出為:Yes, 8 occurs in vector v.
if (binary_search(v.begin(), v.end(), 12)) // vector的查找
cout << "Yes, 12 occurs in vector v.";
else
cout << "No, didn't find 12 in vector v.";
pause();//程序輸出為:No, didn't find 12 in vector v.
where = lower_bound(v.begin(), v.end(), 8); //查找第一次出現8的位置
copy(where, v.end(), out);
pause();//程序輸出為:8 9 11
where = lower_bound(v.begin(), v.end(), 0); //查找第一次出現0的位置
copy(where, v.end(), out);
pause();//程序輸出為:0 0 0 0 0 0 0 4 7 8 9 11
where = upper_bound(v.begin(), v.end(), 0); //查找第一次不出現0時的位置
copy(where, v.end(), out);
pause();//程序輸出為:4 7 8 9 11
vector<int> w(v);
if (v == w) //兩個vector直接比較
cout << "v and w have the same contents";
else
cout << "v and w have different contents";
pause();//程序輸出為:v and w have the same contents
w[5] = 17;
if (v == w)
cout << "v and w have the same contents";
else
cout << "v and w have different contents";
pause();//程序輸出為:v and w have different contents
v[5] = 17;
if (v == w)
cout << "v and w have the same contents";
else
cout << "v and w have different contents";
pause();//程序輸出為:v and w have the same contents
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -