c++類比python 學習(遍歷列表、異常處理、丟擲異常)
阿新 • • 發佈:2018-12-16
遍歷列表
for i in list:
print i
c++11 的特性
1、這種情況是改變i的值並不改變vector,相當於只讀型別,淺拷貝
for(int i:vector) //變數型別必須和容器的基本型別相匹配
{
cout<<i;
}
2、這種情況改變i的值會影響原來的vector,相當於深拷貝
for(auto &i:vector //&i 申明變數是引用型別,auto 是自動將vector的型別複製給i
{
i=0;
cout<<vector<<endl;
}
異常捕獲
python
try:
num=eval ("qq")
except Exception as e:
print(e)
c++
try{
;
}
catch(exception e) //catch(異常類:物件)
{
cout<<e.what()<<endl;
}
丟擲異常
python
raise 異常類(msg)
可以自定義自己的異常,如:
class RangeError(Exception):
def __init__(self,msg):
Exception.__init__(self,msg) #重寫父類的init 函式
example: raise RangeError("out of range" )
c++
#include<stdexcept>
class RangeError:public runtime_error //runtime_error 這個類包括了常用的執行時錯誤
{
public:
RangeError(const string& msg): runtime_error(msg) {}
};