如何在 C++ 中列印出向量的內容

Jinku Hu 2023年10月12日
  1. 使用 for 迴圈與元素訪問記號列印出向量內容的方法
  2. 使用基於範圍的迴圈和元素訪問符號來列印出向量內容
  3. 使用 std::copy 列印出向量內容
  4. 使用 std::for_each 列印出向量內容
如何在 C++ 中列印出向量的內容

本文將介紹幾種在 C++ 中如何列印出向量內容的方法。

使用 for 迴圈與元素訪問記號列印出向量內容的方法

vector 元素可以通過 at() 方法或 [] 操作符來訪問。在這個解決方案中,我們演示了這兩種方法,並用 cout 流列印內容。首先,我們用任意整數初始化向量變數,然後遍歷其元素列印出流。

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  for (size_t i = 0; i < int_vec.size(); ++i) {
    cout << int_vec.at(i) << "; ";
  }
  cout << endl;

  for (size_t i = 0; i < int_vec.size(); ++i) {
    cout << int_vec[i] << "; ";
  }
  cout << endl;

  return EXIT_SUCCESS;
}

輸出:

1; 2; 3; 4; 5; 6; 7; 8; 9; 10;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10;

使用基於範圍的迴圈和元素訪問符號來列印出向量內容

前面的解決方案比較簡單,但看起來很囉嗦。當代 C++ 提供了更靈活的表達迭代的方式,其中之一就是基於範圍的迴圈。當迴圈做相對省力的操作,而且不需要並行化時,它被認為更易讀。

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  for (const auto &item : int_vec) {
    cout << item << "; ";
  }
  cout << endl;

  return EXIT_SUCCESS;
}

使用 std::copy 列印出向量內容

在一條語句中完成向量迭代和輸出操作的一種比較先進的方法是呼叫 <algorithm> 庫中定義的 copy 函式。這個方法接受一個用迭代器指定的向量範圍,作為第三個引數,我們傳遞 ostream_iterator 將範圍內的內容重定向到 cout 流。

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

using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::ostream_iterator;
using std::vector;

int main() {
  vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  copy(int_vec.begin(), int_vec.end(), ostream_iterator<int>(cout, "; "));
  cout << endl;

  return EXIT_SUCCESS;
}

使用 std::for_each 列印出向量內容

另一種在一條語句中完成迭代和輸出操作的 STL 演算法是 for_each。這個方法可以將某個函式物件應用到指定範圍內的每個元素上,這是一個強大的工具。在這種情況下,我們通過 lambda 表示式,將元素列印到輸出流中。

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

using std::cin;
using std::cout;
using std::endl;
using std::for_each;
using std::vector;

int main() {
  vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  for_each(int_vec.begin(), int_vec.end(),
           [](const int& n) { cout << n << "; "; });
  cout << endl;

  return EXIT_SUCCESS;
}
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Vector