我的c++最佳实践

迭代时删除容器中的元素

http://www.cplusplus.com/reference/vector/vector/erase/
http://stackoverflow.com/questions/1604588/iterate-vector-remove-certa...

删除元素可能导致内存变动,因此迭代器会更新它的值,我们应用erase返回的新的迭代器,否则可能导致访问到不应该访问的内存。

for (auto it = container.begin(); it != container.end();) {
    if (condition) {
        it = container.erase(it);
    } else {
        it++;
    }
}

多维数组

http://www.cplusplus.com/forum/articles/7459/

STL vector

#include 
using namespace std;

int main() {
    // construct array2D[HEIGHT][WIDTH]
    vector > array2D;

    array2D.resize(HEIGHT);
    for (int i = 0; i < HEIGHT; ++i)
        array2D[i].resize(WIDTH);


    // construct array3D[HEIGHT][WIDTH][DEPTH]
    vector > > array3D;

    array3D.resize(HEIGHT);
    for (int i = 0; i < HEIGHT; ++i) {
        array3D[i].resize(WIDTH);
        for (int j = 0; j < WIDTH; ++j)
            array3D[i][j].resize(DEPTH);
        }

    return 0;
}

这种方法的好处是不用自己手动释放内存,而且数组大小可以动态变化(不过通常我们使用多维数组时不会变化它的大小)。
缺点是比较丑陋,一串vector会很长,尤其是> >不能连在一起否则编译器会认为是移位或者流提取运算符,尽管在c++11中可以连在一起写了。

指针

int main() {
    // construct p2DArray[HEIGHT][WIDTH]
    double **p2DArray;

    p2DArray = new double*[HEIGHT];
    for (int i = 0; i < HEIGHT; ++i)
        p2DArray[i] = new double[WIDTH];

    for (int i = 0; i < HEIGHT; ++i)
        delete [] p2DArray[i];
    delete [] p2DArray;


    // construct p3DArray[HEIGHT][WIDTH][DEPTH]
    int ***p3DArray;

    p3DArray = new int**[HEIGHT];
    for (int i = 0; i < HEIGHT; i++) {
        p3DArray[i] = new int*[WIDTH];
        for (int j = 0; j < WIDTH;j++) {
            p3DArray[i][j] = new int[DEPTH];
        }
    }

    for (int i = 0; i < HEIGHT; ++i) {
        for (int j = 0; j < WIDTH; ++j) {
            delete [] p3DArray[i][j];
        }
        delete [] p3DArray[i];
    }
    delete [] p3DArray;
}

这样的数组简洁明了,但要自己手动释放内存, 顺序还不能错,比较容易出问题。

你可能感兴趣的:(c++)