選舉日

選舉日

學習練習

簡介

參考

複本與參考

以我們目前所學,想借助函式來更新變數還有點麻煩。 每個函式引數都會被當成複本處理,不會改變原始的值。 視你的型別大小而定,這可能會對程式碼的效能造成嚴重影響。

int adjust_salary(int base, int kids) {
    return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);

// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500

References可以視為別名,對它們所做的變更會影響到原始變數。 References在型別宣告中會使用**& 符號**(&)。

int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;

重新綁定(也就是改變reference的綁定)是做不到的。 你不能有未經初始化的reference。 References必須以一個既有的變數來初始化。

int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000

// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is still -20

int& future_budget;
// => compiler error, reference must be bound!

void

有了references的威力,你或許根本不需要從函式回傳值。 在這種情況下,void會用作回傳型別。

void increase_power(int& level) {
    level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!

說明

你附近的一間學校有個非常活躍的學生會。學生會由一位會長管理,每 2 年會舉辦一次選舉,選出新任會長。

今年的選舉決定要採用一套新的數位系統來計算選票。學校需要你幫忙打造這套新系統。

1. 從ElectionResult取得票數

新系統需要一個能從計數器取得票數的方法。

選舉結果的 struct 已經替你建立好了,定義如下:

struct ElectionResult {
    // Name of the candidate
    std::string name{};
    // Number of votes the candidate has
    int votes{};
};

由於struct中的所有成員都是公開的,你不需要撰寫constructor來初始化ElectionResult物件。 你可以改用initializer list:

ElectionResult hamilton{"Alex", 1804};
// => the hamilton object was initialized with the name "Alex" and 1804 votes.

建立一個函式vote_count,它會接受一個ElectionResult的參考作為引數,並回傳該ElectionResult中的票數。

vote_count(hamilton);
// => 1804

2. 增加ElectionResult的票數

終於要來處理選票了! 現在你需要一個方法,用來增加ElectionResult中的票數。

建立一個void函式increment_vote_count,它會接受一個ElectionResult的參考和一個票數作為引數,並將該ElectionResult增加該票數。

ElectionResult burr{"Aaron " 1801};

increment_vote_count(burr, 3);

vote_count(burr);
// => 1804

3. 計票與會長職位

學校已經交出選票,現在該來確認贏家了。

建立一個函式determine_result,它會接收一份最終計票結果的參考,並回傳新任會長ElectionResult的參考。 它也應該在贏家的名字前面加上「President」。 最終計票結果是以指向std::vector<ElectionResult>的reference形式提供,這是一個 vector,內含所有參選候選人的ElectionResults。

ElectionResult sanchez{"Pedro", 471};
ElectionResult wheatley{"Summer", 340};
std::vector<ElectionResult> final_count{sanchez, wheatley};

ElectionResult& winner = determine_result(final_count);

winner.name;
// => "President Pedro"

為了簡單起見,你可以假設以下幾點:

  • 這個vector至少有一個元素。
  • 第一名不會有平手的情況。
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
C++ Exercism

準備好開始 選舉日 了嗎?

註冊 Exercism,透過 19 個概念100 個練習 和真人引導來學習並精通 C++,全部免費。