C++ 字串陣列


在本節,我們將瞭解如何在 C++ 中定義字串陣列。眾所周知,C 中沒有字串。我們必須使用字元陣列建立字串。因此,要製作一些字串陣列,我們必須製作一個雙維字元陣列。每個行都在該矩陣中儲存不同的字串。

C++ 中有一個名為 string 的類。使用此類物件,我們可以儲存字串型別的資料,並非常高效地使用它們。我們可以建立物件陣列,因此我們可以輕鬆地建立字串陣列。

之後,我們還將瞭解如何建立字串型別的向量物件並將它們用作陣列。

示例

 演示

#include<iostream>
using namespace std;
int main() {
   string animals[4] = {"Elephant", "Lion", "Deer", "Tiger"}; //The
   string type array
   for (int i = 0; i < 4; i++)
      cout << animals[i] << endl;
}

輸出

Elephant
Lion
Deer
Tiger

現在讓我們看看如何使用向量建立字串陣列。向量可在 C++ 標準庫中使用。它使用動態分配的陣列。

示例

 演示

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<string> animal_vec;
   animal_vec.push_back("Elephant");
   animal_vec.push_back("Lion");
   animal_vec.push_back("Deer");
   animal_vec.push_back("Tiger");
   for(int i = 0; i<animal_vec.size(); i++) {
      cout << animal_vec[i] << endl;
   }
}

輸出

Elephant
Lion
Deer
Tiger

更新於: 30-Jul-2019

19K+ 次瀏覽

開始您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.