2010年9月17日 星期五

[C++] STL idiom Vector

  • 基本操作
Vector的STL型式,其實就是以物件導向的方式來操作vector,以物件的方式來操作vector是比較被鼓勵的方式,以下將介紹幾個vector的基本操作。
  • 建構一個元素為空的vector物件:
  • vector<int> ivector;
    
  • 將元素放入vector中,可以使用push_back()
  • for(int i = 0; i < 5; i++) {
        ivector.push_back(i);
    }
    
  • 將元素循序取出,則可以begin()與end()方法分別傳回起始位置的iterator與結束位置的iterator
  • for(vector<int>::iterator it = ivector.begin(); it != ivector.end(); it++) {
    
        cout << *it << " ";
    }
    cout << endl;
    
iterator是標準函式庫定義類別(Class),它是一個指標,指向iterator物件的真正位址,對它進行++的動作,表示移動至 iterator的下一個元素,對它使用*運算子(Dereferences operator),表示提取出iterator目前位址的值,如果iterator走訪至結束位置的iterator的位址,表示元素走訪完畢。

可以使用下標運算子[ ]來存取vector的元素,但實際上要知道vector與陣列本質上是不相同的,如最上頭那樣宣告一個空的vector物件時,其容量(capacity)為0,長度(size)也為0,所以此時不能使用ivector[0]來取得第一個元素值,因為實際上ivector中還沒有任何的元素。

當使用push_back()將元素加入vector時,vector的長度會自動增長,由於每次增長度都要配置記憶體過於沒有效率,所以vector會自動先增加足夠的容量,當元素的長度超過容量時,才會再重新配置新的容量,可以使用capacity()取得vector容量,使用size()取得元素長度。
#include <iostream>
#include <vector>
using namespace std; 

int main() { 
    vector<int> ivector;
 
    for(int i = 0; i < 10; i++) {

        ivector.push_back(i);
    }
 
    for(vector<int>::iterator it = ivector.begin(); it != ivector.end(); it++) {
 
        cout << *it << " ";
    }
    cout << endl;
 
    cout << "capacity: " << ivector.capacity() << endl
         << "size: " << ivector.size() << endl;
 
    return 0; 
}
執行結果
0 1 2 3 4 5 6 7 8 9
capacity: 16
size: 10
  • Vector演算
對vector進行排序、尋找、反轉等操作,可以使用標準函式庫中的泛型演算法,要使用泛型演算法必須先含入表頭檔:
#include <algorithm>
下面這個程式直接示範了排序、尋找、反轉等操作:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std; 

int main() { 
    int iarr[] = {30, 12, 55, 31, 98, 11, 41, 80, 66, 21};
    vector<int> ivector(iarr, iarr + 10);
 
    // 排序 
    sort(ivector.begin(), ivector.end());
 
    for(vector<int>::iterator it = ivector.begin(); it != ivector.end(); it++) {
 
    cout << *it << " ";
    }
    cout << endl;

    cout << "輸入搜尋值:";
    int search = 0;
    cin >> search;
                              // 搜尋
    vector<int>::iterator it = find(ivector.begin(), ivector.end(), search);
 
    if(it != ivector.end()) {
        cout << "找到搜尋值!" << endl;
    }
    else {
        cout << "找不到搜尋值!" << endl;
    }
 
    // 反轉 
    reverse(ivector.begin(), ivector.end());
 
    for(vector<int>::iterator it = ivector.begin();
        it != ivector.end();
        it++) {
 
        cout << *it << " ";
    }
    cout << endl;
 
    return 0; 
}
11 12 21 30 31 41 55 66 80 98
輸入搜尋值:41
找到搜尋值!
98 80 66 55 41 31 30 21 12 11

2010年9月14日 星期二

[C++] 標準類型轉換:static_cast, dynamic_cast, reinterpret_cast, and const_cast

  • static_cast
    • 可用於轉換基底類別指標為衍生類別指標,也可用於傳統的資料型態轉換。
    舉例來說,在指定的動作時,如果右邊的數值型態比左邊的數值型態型態長度大時,超出可儲存範圍的部份會被自動消去,例如將浮點數指定給整數變數,則小數的部份會被自動消去,例子如下,程式會顯示3而不是3.14:
    int num = 0;
    double number = 3.14;
    num = number;
    cout << num;
    
    由於失去的精度,在編譯時編譯器會提出警訊: [Warning] converting to `int' from `double' 如果確定這個動作是您想要的,那麼您可以使用顯式型態轉換(Explicit type conversion)或稱之為強制轉型(Cast),例如:
    int num = 0; 
    double number = 3.14; 
    num = static_cast(number);
    
    在兩個整數型態相除時,您也可以進行型態轉換,將其中一個型態轉換至double型態再進行運算,下例會顯示3.3333:
    int number = 10;
    cout << static_cast<double>(number) / 3;
    
    static_cast是Standard C++新增加的轉型語法,在這之前顯式型態轉換可以使用以下的舊語法,基於向後相容,Standard C++仍支援這種舊語法,但鼓勵使用新風格的語法
    int number = 10;
    cout << (double) number/ 3;
    
  • dynamic_cast
  • 使用static_cast(甚至是傳統的C轉型方式)將基底類別指標轉換為衍生類別指標,這種轉型方式稱為強制轉型,但是在執行時期使用強制轉型有危險性,因為編譯器無法得知轉型是否正確,執行時期真正指向的物件型態是未知的,透過簡單的檢查是避免錯誤的一種方式:
    if(typeid(*base) == typeid(Derived1)) {
        Derived1 *derived1 = static_cast<derived1*>(base);
        derived1->showOne();
    }
    
    為了支援執行時期的型態轉換動作,C++提供了dynamic_cast用來將一個基底類別的指標轉型至衍生類別指標,稱之為「安全向下轉型」(Safe downcasting),它在執行時期進行型態轉換動作,首先會確定轉換目標與來源是否屬同一個類別階層,接著才真正進行轉換的動作,檢驗動作在執行時期完成,如果是一個指標,則轉換成功時傳回位址,失敗的話會傳回0,如果是參考的話,轉換失敗會丟出bad_cast例外。 可以將執行時期型態資訊(RTTI)中的showWho()函式如下修改:
    void showWho(Base *base) {
        base->foo();
        
        if(Derived1 *derived1 = dynamic_cast>derived1*<(base)) {
            derived1->showOne();
        }
        else if(Derived2 *derived2 = static_cast>derived2*<(base)) {
            derived2->showTwo();    
        } 
    }
    
    由於dynamic_cast轉換失敗的話會傳回0,因而運算的結果不可使用,必須先行對轉換結果作檢查才可以,如上例所示。 如果使用參考的話,dynamic_cast在轉換失敗之後會丟出bad_cast例外,所以您必須使用try...catch來處理例外,例如:
    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    class Base {
    public:
        virtual void foo() = 0;
    };
    
    class Derived1 : public Base {
    public:
        void foo() {
            cout << "Derived1" << endl;
        }
    
        void showOne() {
            cout << "Yes! It's Derived1." << endl;
        }
    };
    
    class Derived2 : public Base {
    public:
        void foo() {
            cout << "Derived2" << endl;
        }
     
        void showTwo() {
            cout << "Yes! It's Derived2." << endl;
        }
    }; 
    
    void showWho(Base &base) {
        try {
            Derived1 derived1 = dynamic_cast<derived1&>(base);
            derived1.showOne();
        }
        catch(bad_cast) {
            cout << "bad_cast 轉型失敗" << endl;
        }
    }
    
    int main() { 
        Derived1 derived1;
        Derived2 derived2;
    
        showWho(derived1);
        showWho(derived2);
    
        return 0;
    }
    
    執行結果(使用dynamic_cast):
    Yes! It's Derived1.
    bad_cast 轉型失敗
    執行結果(使用static_cast):
    Yes! It's Derived1.
    Yes! It's Derived1.
  • reinterpret_cast
    • 用於將一種型態的指標轉換為另一種型態的指標,例如將char*轉換為int*
    #include <iostream>
    using namespace std;
    
    int main() {
        int* i;
        char* str = "test";
    
        i = reinterpret_cast<int>(str);
        cout << i << endl;
    
        return 0;
    } 
    
    (可能)執行結果:
    134514704
  • const_cast
    • const_cast用於一些特殊場合可以覆寫變數的const屬性,利用cast後的指標就可以更改變數的內部。
    使用格式:
    const_cast<常量(const)型態(指標) / 非常量型態(指標)>( 非常量變數(指標) / 常量變數(指標) );
    
    使用範例:
    #include <iostream>
    using namespace std; 
    
    void foo(const int*);
    
    int main() {
        int var = 10;
    
        cout << var << endl;
    
        foo(&var);
    
        cout << var << endl;
    
        return 0;
    }
    
    void foo(const int* p) {
        int *v = const_cast<int *>(p);
        *v = 20;
    }
    
    執行結果:
    10
    20

Qt4 學習筆記(八):Custom Event and Post Event

  • Custom Event and Post Event
自訂事件類型,最簡單的方式,是透過QEvent::Type指定事件類型的常數值,在建構QCustomEvent時作為建構引數並透過postEvent()傳送事件,例如:
const QEvent::Type MyEvent = (QEvent::Type) 9393;
...
QApplication::postEvent(object, new QCustomEvent(MyEvent));
自訂事件必須定義事件號碼(Event number),自定義的事件號碼必須大於QEvent::Type的列舉值,通常1024以下的值是保留給Qt預先定義的事件類型來使用。object是事件的接受者,使用 postEvent()方法時,事件必須以new的方式建立,在事件處理完畢之後,會自動將事件delete,postEvent()會將事件放至事件佇列的尾端,然後立即返回。若要強迫Qt馬上處理先前postEvent()排到佇列的事件,則可以使用sendPostedEvents()。
您可以使用sendEvent()方法,事件會立即送至接受者,sendEvent()方法的事件不會被delete,所以通常建立在堆疊(Stack)區,例如:
CustomEvent event("Event Message");
QApplication::sendEvent(object, &event);
自訂的事件類型必須是QEvent的子類別,通常繼承QCustomEvent類別,建立自訂事件類別可以獲得更多的型態安全(Type safety)。

  • 要處理自訂事件,可以重新定義customEvent()方法,例如:
void CustomWidget::customEvent(QCustomEvent *event) {
    CustomEvent *customEvent = static_cast<CustomEvent *>(event);
    ....
}
  • 或是重新定義event()方法,將自訂事件分派給其它函式或直接在event()中處理,例如:
bool CustomWidget::event(QEvent *event) {
    if (event->type() == MyCustomEventType) {
        CustomEvent *myEvent = static_cast<CustomEvent *>(event);
        // 對自訂事件的處理,或呼叫其它函式來處理事件
        return true;
    }
    return QWidget::event(event);
}