C++ 打印 vector

打印 1D vector

方法一: 使用基本 for 循环

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<int> arrays{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for(int i = 0; i < arrays.size(); ++i) {
        std::cout << arrays[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

方法二: 使用 for each 循环方法

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<int> arrays{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for(auto array: arrays) {
        std::cout << array << " ";
    }
    std::cout << std::endl;

    return 0;
}

方法三: 使用 iterator 方法

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<int> arrays{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for(auto it = arrays.begin(); it != arrays.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

方法四:使用 ostream_iterator

#include <iostream>
#include <vector>
#include <iterator>

int main() {
    // initial a vector
    std::vector<int> arrays{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    std::ostream_iterator<int> it(std::cout, " ");
    std::copy(arrays.begin(), arrays.end(), it);

    return 0;
}

方法五:std::for_each

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // initial a vector
    std::vector<int> arrays{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    std::for_each(arrays.begin(), arrays.end(), [](const auto &i){std::cout << i << " "; });
    std::cout << "\n";

    return 0;
}

打印 2D vector

方法一:index for 循环

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<std::vector<int>> arrays{ {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};

    for(int i = 0; i < arrays.size(); ++i) {
        for(int j = 0; j < arrays[0].size(); ++j) {
            std::cout << arrays[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

方法二: for each 循环

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<std::vector<int>> arrays{ {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};

    for(auto &array: arrays) {
        for(auto &arr: array ) {
            std::cout << arr << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

方法三:使用 iterator 指针

#include <iostream>
#include <vector>

int main() {
    // initial a vector
    std::vector<std::vector<int>> arrays{ {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};

    for(auto ita = arrays.begin(); ita != arrays.end(); ++ita) {
        for(auto it = ita->begin(); it != ita->end(); ++it) {
            std::cout << *it << " ";
        }
        std::cout << "\n";
    }

    return 0;
}
posted @ 2020-01-31 14:52  busyboxs  阅读(3147)  评论(2编辑  收藏  举报