zoukankan      html  css  js  c++  java
  • dfadsfa

    dfadsfa

    Linux 下C++学习笔记1

    string 表示可变长的字符序列,vector 存放的是某种给定类型对象的可变序列。

    C++ 标准要求,vector 应该能在运行时搞笑快速的添加元素。因此既然vector 对象能高效的增长,那么在定义vector对象时,设定其大小也就没有什么必要了,事实上如果这么做,性能可能会更差。

    范围for 语句体内不应该改变其所遍历对象序列的大小

    #include <iostream>
    #include <string>
    #include <vector>
    
    using std::cin;
    using std::cout;
    using std::endl;
    using std::string;
    using std::vector;
    
    vector<int> test_int;
    
    int main()
    {
        for (int i=0; i < 100; ++i) {
            test_int.push_back(i);
        }
    
        for (int j : test_int) {
            cout << j << endl;
        }
        return 0;
    }

    不能将数组的内容拷贝给其他数组作为初始值,也不能用数组为其他数组赋值。

    指针加上一个整数所得的结果还是一个指针

    使用数组的时候其实真正用的是指向数组首元素的指针。

    对于大多数应用来说,使用标准库string要比使用C风格字符串更加安全、更加高效

    现代的C++ 程序应当尽量使用vector 和迭代器,避免使用内置数组和指针;应该尽量使用string,避免使用C风格的基于数组的字符串。

    严格来说,C++中没有多维数组,通常所说的多维数组其实是数组的数组。谨记这一点,对今后理解和使用多维数组大有益处。

    //遍历多维数组
    int main()
    {
        //大小为1的数组,每个数组中含有2个数组元素。
        //每个数组元素中含有5个整型值
        int test_int[1][2][5] = {
                {
                        {
                                {1},{2},{3},{4},{5}
                        },
                        {
                                {6},{7},{8},{9},{10}
                        },
                }
        };
    
        //遍历多维数组
        for (auto &a : test_int) {
            for (auto &b : a) {
                for (auto c : b) {
                    cout << c << endl;
                }
            }
        }
        
       return 0;
    }

    要使用范围for语句处理多维数组,除了最内层的循环外,其他所有的循环控制变量都应该是引用类型。

    int *ip[4];   // 是个数组,整形指针的数组,含有4个int型指针
    int (*ip)[4]; // 是个指针,指向含有4个整数的的数组

    可以在if switch 、while 、和for 语句的控制结构内定义变量。定义在控制结构当中的变量只在相应的语句内部可见,一旦语句结束,变量也就超出其作用范围了。

    PHP 代码

    roverliang$ cat demo.php 
    <?php
    
    
    for($i=0; $i< 100; $i++ ) {
    
    //do some thing;
    
    }
    
    echo $i.PHP_EOL;
    
    roverliang$ php demo.php 
    100
    roverliang$ 

    C++ 代码

    int main()
    {
       for (int i=0; i < 100; ++i) {
           //
       }
        cout << i << endl;
       return 0;
    }
    
    //error: use of undeclared identifier 'i'
    //cout << i << endl;
                ^
    
  • 相关阅读:
    c++ new 堆 栈
    c++ int 负数 补码 隐式类型转换
    python json 序列化
    %pylab ipython 中文
    matplotlib中什么是后端
    IPython 4.0发布:Jupyter和IPython分离后的首个版本
    ipython
    python 类
    python 高级特性
    windows网络模型
  • 原文地址:https://www.cnblogs.com/roverliang/p/8016546.html
Copyright © 2011-2022 走看看