关闭

C++ 与 python 语法 对比

标签: python
877人阅读 评论(0) 收藏 举报
分类:

C++ 与 python 语法 对比

flyfish

变量定义
//C++
    int a = 8, b = 9;

    //python
    i = 10
    print(i)
条件语句
//C++
    if (a > b)
    {
        std::cout << a << " is max" << std::endl;
    }
    else if (a == b)
    {
        std::cout << a << " is equal to " << b << std::endl;
    }
    else
    {
        std::cout << b << " is max" << std::endl;
    }

    //python

    if a > b:
    print(a, 'is max')
        elif a == b :
        print(a, 'is equal to', b)
    else:
    print(b, 'is max')
循环语句
//C++
    int c[3] = { 10, 11, 12};
    for (int i = 0; i < 3; i++)//C++98
    {
        std::cout << c[i] << std::endl;
    }
    for (auto i : c)//C++11
    {
        std::cout << i << std::endl;
    }

    //python
    myarray = [10, 11, 12]
        for i in myarray :
    print(i)
元组
//C++
    auto mytuple = std::make_tuple(5, 6, 7);
    std::cout << std::get<0>(mytuple) << std::endl;

    //解析多个独立变量std::ignore 表示忽略该变量的解析
    int x, y, z=0;
    std::tie(x,y,std::ignore)= mytuple;
    std::cout << std::get<0>(mytuple) << std::endl;

    //python
    mytuple = (5, 6, 7)
        print(mytuple[0])

    x, y, z = mytuple
    print(x)
向量
//C++
    auto myvec = std::vector<int>{ 1, 2, 3, 4 };
    myvec.push_back(5);

    //python
    myvec = [1, 2, 3, 4]
        myvec.append(5);
键值对
    //C++
    std::map<int, const char*>(mymap) = { { 1, "a" }, { 2, "b" } };

    std::map<int, const char*>::const_iterator it;
    for (it = mymap.begin(); it != mymap.end(); ++it)
        std::cout << it->first << "=" << it->second << std::endl;

    //python
    mymap = { 1: "a", 2 : "b" }
    print(mymap[1])


    for key in mymap :
        print(key, '=', mymap[key])

    for key, value in mymap.items() :
        print(key, '=', value)

函数定义

//C++
void myfunction(int parameter)
{

}
//python
def pyfunction(parameter) :
print(parameter)
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:651540次
    • 积分:10122
    • 等级:
    • 排名:第1755名
    • 原创:364篇
    • 转载:0篇
    • 译文:2篇
    • 评论:102条
    博客专栏