Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การพิมพ์เนื้อหา Vector ใน C++

Vector เป็น Dynamic Array ที่ปรับขนาดได้ ใช้ std::vector จาก <vector>

ตัวอย่างโค้ด

#include <iostream>
#include <vector>

void print(const std::vector<int>& a) {
    std::cout << "The vector elements are : ";
    for (size_t i = 0; i < a.size(); i++)
        std::cout << a.at(i) << ' ';
}

int main() {
    std::vector<int> a = {2, 4, 3, 5, 6};
    print(a);
    return 0;
}

ผลลัพธ์

The vector elements are : 2 4 3 5 6

วิธีอื่นๆ

// Range-based for (C++11)
for (const auto& elem : vec)
    std::cout << elem << ' ';

// Iterator
for (auto it = vec.begin(); it != vec.end(); ++it)
    std::cout << *it << ' ';

// std::copy กับ ostream_iterator
#include <algorithm>
#include <iterator>
std::copy(vec.begin(), vec.end(), 
          std::ostream_iterator<int>(std::cout, " "));

Range-based for เป็นวิธีที่แนะนำใน Modern C++ (กระชับ อ่านง่าย ปลอดภัย)