作为新人,刚学数据结构与算法,啥都不会,希望路过的大佬勿喷我。。。
第一章,主要讲了一下一些基本级数以及c++的语法(大多数是类和泛式编程 ,作为一个刚学c++的的人当然要看一下了。。。我连泛式编程都没见过。。。tcl…)
我做了一些课后习题,希望能给一些和我一样新学数据结构的人一些参考
- 选择问题
我只会插入排序。。。
#include<iostream>
using namespace std;
int main(){
vector<int>a{1,3,456,78,43,2345,668,234,890,348};//c++11原则,老版编译器不允许
int i,j,key
for( i=1;i<a.size();++i)
{
int key=a[i];
j=i-1;
while(j>=0&&a[j]>key)
{
a[j+1]=a[j];
}
a[j+1]=key;
}
}
2.编写一个递归函数,它返回数n的二进制表示中1的个数。利用如下事实:如果n是奇数,那么它等于n/2的二进制表示中1的个数加1
#include<iostream>
using namespace std;
int f1(int a){
if(a<2)
return a;
else return a%2+f1(a/2);
}
int main(){
int a=3;
cout<<f1(a);
}
类模板,刚学不会用,之后熟练再补。。。
- 定义一个rectangle类,该类提供getlength,getwidth,
#include<iostream>
#include<vector>
using namespace std;
template<typename object>
class matrix
{
public:
matrix(int rows,int cols):array(rows)
{
for(auto&thisrow:array)
array.resize(cols);
}
const vector<object> & operate[](int row)const
{
return array[row];
}
vector<object>& operator[](int row)
{
return array[row];
}
int getwidth()
{
return array.size();
}
int getlength()
{
return getwidth?array[0].size():0;
}
private:
vector<vector<object>>array;
};
class comparebyarea
{
public:
bool operator()(const matrix &a1,const matrix &a2) const
{
return a1.getwidth*a1.getlength<a2.getwidth*a2.getlength;
}
};
class comparebylong
{
public:
bool operator()(const matrix &a1,const matrix &a2) const
{
return a1.getwidth+a1.getlength<a2.getwidth+a2.getlength;
}
};
4.对于matrix类,添加成员函数resize,以及零参数构造函数
class matrix
{
public:
matrix(int rows,int cols):array(rows)
{
for(auto&thisrow:array)
thisrow.resize(cols);
}
matrix():array(1)
{
array[0].resize(1);
}
matrix& resize(int a,int b)
{
array.resize(a);
for(auto&thisrow:array)
thisrow.resize(b);
}
const vector<object> & operate[](int row)const
{
return array[row];
}
vector<object>& operator[](int row)
{
return array[row];
}
int getwidth()
{
return array.size();
}
int getlength()
{
return getwidth?array[0].size():0;
}
private:
vector<vector<object>>array;
};