⑴ 泛型算法unique_的问题
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
using namespace std;
int main()
{
�0�2int a[]={1,2,3,4,3,5};
�0�2list<int> ilst(a,a+6);
ilst.sort(); �0�2 // 这里需要排序,不排序,unique_不起作用�0�2vector<int> ivec;
�0�2unique_(ilst.begin(),ilst.end(),back_inserter(ivec));
�0�2for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)
�0�2 cout<<*iter<<" ";
�0�2cout<<endl;
�0�2return 0;
}
⑵ c++的程序
其实排序,在C++的泛型算法里有一个 sort() ,直接利用它就不用自己写代码,又简洁,又省力。
我把1 2的代码入在一个main()里
#include <iostream>
#include <cstdlib> //随机数产生头文件
#include <ctime> //包含time()的头文件
#include <vector>
#include <algorithm> //泛型算法头文件
using std::cout;
using std::endl;
using std::cin;
using std::vector;
int main(void)
{
/* 1小题部分 */
int rezult = 1;
int temp = 0;
cout << "please input the number of the end:" << endl;
cin >> temp; //交互部分,输入阶乘上限
while(temp)
{
rezult *= temp--;
}
cout << "rezult:" << rezult << endl << '\n'; // 结果
/* 2小题部分 */
int num = 0;
int rd = 0;
vector<int> TR;
srand(time(0));
cout << "input the number :" << endl;
cin >> num; //输入需要产生随机数的个数,10则输入10
while(num != 0)
{
rd = rand() % 101;
if(rd % 2 != 0 )
TR.push_back(rd);
else
continue;
--num;
}
vector<int>::iterator first = TR.begin();
sort(first, TR.end()); //利用泛型算法对数排序
while(first != TR.end())
{
cout << *first << " "; // 输出排序后的数
++first;
}
cout << endl;
return 0;
}
⑶ c++泛型算法中replace的问题
能学到STL的算法已经恨牛逼了。
应该改成
replace(sevc.begin(),sevc.end(),string("hello"),string("haha"));
因为算法中使用模板做形参,所以需要明确类型信息。直接写"hello"编译器不知道该处理成什么类型,所以出错。