1. 程式人生 > >使用常量引用形式,將map作為形參傳遞時的問題

使用常量引用形式,將map作為形參傳遞時的問題

void test(const unordered_map<int,int> &um){
  if(um[1]){
    //一段測試程式碼
  }
}

上述程式碼將不能通過編譯。

原因:map的[]運算子會在索引項不存在的時候自動建立一個物件,而常量不能改變。

解決辦法:使用迭代器替換即可,如下例所示。

void test(const unordered_map<int,int> &um) {
	unordered_map<int, int>::const_iterator it = um.begin();
	for (; it != um.end(); ++it) {
		//balabala
	}
}

注意:

因為傳入的um引數是常量型別的,因此um.begin()也是常量指標,因此只能將其賦值給常量指標const_iterator。