如何在 C++ 中將資料三元組儲存在向量中?


在本教程中,我們將討論一個程式,以瞭解如何在 C++ 中將資料三元組儲存在向量中。

要將三個元素儲存在向量的單個單元格中,我們將建立一個使用者定義的結構,然後根據該使用者定義的結構建立一個向量。

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
struct Test{
   int x, y, z;
};
int main(){
   //creating a vector of user defined structure
   vector<Test> myvec;
   //inserting values
   myvec.push_back({2, 31, 102});
   myvec.push_back({5, 23, 114});
   myvec.push_back({9, 10, 158});
   int s = myvec.size();
   for (int i=0;i<s;i++){
      cout << myvec[i].x << ", " << myvec[i].y << ", " << myvec[i].z << endl;
   }
   return 0;
}

輸出

2, 31, 102
5, 23, 114
9, 10, 158

更新於:2020 年 3 月 2 日

569 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告