Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách in nội dung vector trong C++

std::vector là mảng động tự resize. Phần tử lưu liên tục, truy cập O(1).

Các cách in vector

1. Range-based for (C++11) - Khuyến nghị nhất

#include <iostream>
#include <vector>

int main() {
    std::vector v = {2, 4, 3, 5, 6};
    
    for (const auto& x : v) {
        std::cout << x << ' ';
    }
    std::cout << '\n';
    return 0;
}

2. Index loop (Truy cập ngẫu nhiên)

for (size_t i = 0; i < v.size(); ++i) {
    std::cout << v[i] << ' ';        // operator[] - không check bounds
    // hoặc
    std::cout << v.at(i) << ' ';     // at() - check bounds, throw out_of_range
}

3. Iterator (C++98 style)

for (auto it = v.begin(); it != v.end(); ++it) {
    std::cout << *it << ' ';
}

// C++11: auto
for (std::vector::const_iterator it = v.cbegin(); it != v.cend(); ++it) { ... }

4. Algorithm + ostream_iterator (Functional style)

#include 
#include 

std::copy(v.begin(), v.end(), 
          std::ostream_iterator(std::cout, " "));
std::cout << '\n';

5. C++20: ranges + views

#include 
#include 

std::cout << std::format("{}", v | std::views::join_with(' ')) << '\n';
// Hoặc đơn giản:
for (int x : v) std::cout << x << ' ';

6. In vector của custom type

struct Point { int x, y; };
std::vector pts = {{1,2}, {3,4}};

for (const auto& p : pts) {
    std::cout << "(" << p.x << "," << p.y << ") ";
}
// Hoặc overload operator<<
std::ostream& operator<<(std::ostream& os, const Point& p) {
    return os << "(" << p.x << "," << p.y << ")";
}
// Sau đó:
std::copy(pts.begin(), pts.end(), 
          std::ostream_iterator(std::cout, " "));

Ví dụ hàm in tái sử dụng

template <typename T>
void printVector(const std::vector<T>& vec, const char* delimiter = " ") {
    for (size_t i = 0; i < vec.size(); ++i) {
        std::cout << vec[i];
        if (i + 1 < vec.size()) std::cout << delimiter;
    }
    std::cout << '\n';
}

// Sử dụng
printVector(v);        // "2 4 3 5 6"
printVector(v, ", ");  // "2, 4, 3, 5, 6"

Kết quả

2 4 3 5 6

Lưu ý hiệu năng

  • operator[] nhanh nhất (no bounds check)
  • at() an toàn hơn (throw exception)
  • Range-based for tối ưu hóa tốt
  • Tránh copy vector khi truyền hàm: dùng const vector<T>&