Posted on

C++ Inheritance

#include <iostream>

using namespace std;

class Base
{
public:
    Base()
    {
        echo();
    }

    void echo()
    {
        cout << "Base\n";
    }
};

class Derived
        :
        public Base
{
public:
    Derived()
    {
        echo();
    }

    void echo()
    {
        cout << "Derived\n";
    }
};
int main() {
    Base* a = new Derived();
    a->echo();

    return 0;
}

Swap with Zero

Only swap with the number zero is allowed in the sorting.

#include <iostream>

using namespace std;

/**
 * 交换数组里n和0的位置
 * array: 存储[0-n)的数组
 * len: 数组长度
 * n: 数组里要和0交换的数
 */
void swap_with_zero(int* array, int len, int n)
{
    int pos_zero, pos_n;
    for(int i = 0; i < len; ++i) {
        if(array[i] == 0) pos_zero = i;
        if(array[i] == n) pos_n = i;
    }
    swap(array[pos_zero], array[pos_n]);
}


class Solution {
public:
    /**
     * 调用方法swap_with_zero来对array进行排序
     */
    void sort(int* array, int len) {
        bool isFound = false;
        while(!isFound) {
            if(array[0] == 0) {
                for(int i = 0; i < len; ++i) {
                    if(array[i] != i) {
                        swap_with_zero(array, len, array[i]);
                        break;
                    } else {
                        if(i == len - 1) {
                            isFound = true;
                            break;
                        }
                    }
                }
            }

            for(int i = 0; !isFound && i < len; ++i) {
                if(array[i] == 0) {
                    swap_with_zero(array, len, i);
                    break;
                }
            }
        }
    }
};

int main() {
    Solution sol;
    int array[] = {2, 3, 0, 5, 1, 4};
    sol.sort(array, 6);
    for(int i = 0; i < 6; ++i) {
        cout << array[i];
    }
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *