1.C++中list容器实现
using namespace std;
int main()
{
list<int> l1;
l1.assign(2,3);
list<int>::iterator n = l1.begin();
for(n = l1.begin();n!=l1.end();n++)
{
cout << *n << "\t";
}
cout << endl;
cout << "last one =" << l1.back() <<endl;
cout << "l1.empty =" << l1.empty() <<endl;
cout << endl << "insert" << endl;
l1.insert(l1.begin(),1);
l1.insert(l1.begin(),2);
l1.insert(l1.begin(),2,3);
l1.insert(l1.begin(),4);
for(n = l1.begin();n!=l1.end();n++)
{
cout << *n << "\t";
}
cout << endl << "delete tail" << endl;
l1.pop_back();
for(n = l1.begin();n!=l1.end();n++)
{
cout << *n << "\t";
}
cout << endl << "**********" << endl;
cout << "size =" << l1.size() <<endl;
cout << "front=" << l1.front() <<endl;
cout << "max_size =" << l1.max_size() << endl;
cout << endl << "sort" << endl;
l1.sort();
for(n = l1.begin();n!=l1.end();n++)
{
cout << *n << "\t";
}
cout << endl << "**********" << endl;
cout << endl << "remove" << endl;
l1.remove(3);
for(n = l1.begin();n!=l1.end();n++)
{
cout << *n << "\t";
}
cout << endl << "**********" << endl;
return 0;
}
2.实现一个类,类中实现一个set函数,设置-一个成员a的值。实现Sum函数,打印1~成
员a的值之间所有数字之和,实现Porduct函数,打印1~a的值之间所有数字的乘积,实现
函数PrimeNumber,输出1~a 的值之间的所有质数。
例如,调用set 输入5, sum 结果15,Porduct 结果120, PrimeNumber结果 3, 5
#include <iostream>
using namespace std;
template<typename T>
class AA
{
T a;
public:
void set(T a)
{
this->a=a;
}
T Sum()
{
T sum = 0;
for(int i=1;i<=a;i++)
sum+=i;
cout << "sum = " << sum << endl;
return sum;
}
T Product()
{
T multiply = 1;
for(int i=1;i<=a;i++)
multiply*=i;
cout << "multiply = " << multiply << endl;
return multiply;
}
void PrimeNumber()
{
int count = 0;
for(int i=2;i<=a;i++)
{
count = 0;
for(int j=2;j<=a-1;j++)
{
if(i%j==0&&i!=j)
{
count++;
break;
}
}
if(count==0)
{
cout<< i << endl;
}
}
}
};
int main()
{
AA<int> a;
a.set(10);
a.Sum();
a.Product();
a.PrimeNumber();
return 0;
}