数据结构与算法分析c++描述_第一章初读

作为新人,刚学数据结构与算法,啥都不会,希望路过的大佬勿喷我。。。
第一章,主要讲了一下一些基本级数以及c++的语法(大多数是类和泛式编程 ,作为一个刚学c++的的人当然要看一下了。。。我连泛式编程都没见过。。。tcl…)
我做了一些课后习题,希望能给一些和我一样新学数据结构的人一些参考

  1. 选择问题

我只会插入排序。。。

#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);

}

类模板,刚学不会用,之后熟练再补。。。

  1. 定义一个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;
    
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值