没有合适的资源?快使用搜索试试~ 我知道了~
程序设计艺术与方法.doc
需积分: 8 0 下载量 9 浏览量
2022-10-14
23:56:54
上传
评论
收藏 92KB DOC 举报
温馨提示
试读
25页
程序设计艺术与方法.doc
资源推荐
资源详情
资源评论
程序设计艺术与措施
实验一 STL 的熟悉与使用
1. 实验目的 (1) 掌握 C++中 STL 的容器类的使用。 (2) 掌握 C++中 STL 的算法类
的使用。
2. 实验设备 硬件环境:PC 计算机 软件环境: 操作系统:Windows / Windows XP /
Linux 语言环境:Dev cpp / gnu c++
3. 实验内容 (1) 练习 vector 和 list 的使用。 定义一种空的 vector,元素类型为 int,
生成 10 个随机数插入到 vector 中,用迭代 器遍历 vector 并输出其中的元素值。在
vector 头部插入一种随机数,用迭代器遍历 vector 并输出其中的元素值。用泛型算法 find
查找某个随机数,如果找到便输出,否则将此数 插入 vector 尾部。用泛型算法 sort 将
vector 排序,用迭代器遍历 vector 并输出其中的元 素值。删除 vector 尾部的元素,用迭
代器遍历 vector 并输出其中的元素值。将 vector 清 空。 定义一种 list,并反复上述实验,
并注意观测成果。 (2) 练习泛型算法的使用。
- 149
定义一种 vector,元素类型为 int,插入 10 个随机数,使用 sort 按升序排序,输
出 每个元素的值,再按降叙排序,输出每个元素的值。练习用 find 查找元素。用 min 和
max 找出容器中的小元素个大元素,并输出。
源代码:
#include <iostream>
#include <vector>
#include<iomanip>
#include<ctime>
#include <algorithm>
using namespace std;
vector<int> myV;
bool sortup(int v1,int v2)
{
return v1<v2;
}
int main(int argc, char *argv[])
{
srand(time(NULL));
for (int i=0;i<10;i++)
myV.push_back(rand());
sort(myV.begin(),myV.end(),sortup);
vector<int>::iterator it1;
for (it1=myV.begin();it1!=myV.end();it1++)
{
cout<<(*it1)<<setw(6);
}
cout<<endl;
int min=myV[0];
for (it1=myV.begin()+1;it1!=myV.end();it1++)
if((*it1)<min)min=(*it1);
cout<<"最小元素为" <<min<<endl;
int max=myV[0];
for (it1=myV.begin();it1!=myV.end();it1++)
if((*it1)>max)max=(*it1);
cout<<"最大元素为" <<max<<endl;
cout<<endl;
int value=rand();
it1=find(myV.begin(),myV.end(),value);
if((*it1)==value)
cout<<"找到了这个随机数"<<endl ;
else
cout<<"没有找到这个随机数"<<endl;
myV.insert(myV.end(),value);
cout<<"插入尾部的随机数为"<<value<<endl;
for (it1=myV.begin();it1!=myV.end();it1++)
{
cout<<(*it1)<<setw(6);
}
cout<<"\n"<<endl;
int t=rand();
myV.insert(myV.begin(),t);
cout<<"插入头部的随机数为" <<t<<endl;
for (it1=myV.begin();it1!=myV.end();it1++)
{
cout<<(*it1)<<setw(6);
}
cout<<endl;
myV.pop_back ();
for (it1=myV.begin();it1!=myV.end();it1++)
{
cout<<(*it1)<<setw(6);
}
cout<<endl;
myV.clear();
if(myV.empty())
{
cout << "It's empty!" << endl;
}
system("PAUSE");
return 0;
}
运营截图:
2 练习泛型算法的使用:
源代码:
#include<list>
#include<iostream>
//#inclued<algorithm>
using namespace std;
typedef list<int> lin;
int value[]={1,2,3,4,5};
void print(lin &l)
{
int i;
lin::iterator lit;
for(lit=l.begin();lit!=l.end();lit++)
cout<<(*lit)<<" ";
剩余24页未读,继续阅读
资源评论
智慧安全方案
- 粉丝: 3675
- 资源: 59万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功