CHAPTER6-24.cpp
上传用户:fjc899
上传日期:2007-07-03
资源大小:187k
文件大小:3k
- //文件名:CHAPTER6-24.cpp
- #include <vector>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- void pause() //程序暂停
- { char c;
- cout << "nnPress return to continue: ";
- cin.get(c);
- cout << "nn";
- }
- 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;
- }