如何將struct塞進vector? (C/C++) (STL)

來源:互聯網
上載者:User

Abstract
一個很常見的需求:『將struct塞進vector』,在C++該怎麼做呢?

Introduction
使用環境:Visual C++ 9.0 / Visual Studio 2008

由於vector只允許一個欄位,所以才會想將struct塞進vector,以彌補vector的不足。

struct_in_vector.cpp / C++

1  /* 
2  (C) OOMusou 2008 http://oomusou.cnblogs.com
3  
4  Filename    : struct_in_vector.cpp
5  Compiler    : Visual C++ 9.0 / Visual Studio 2008
6  Description : Demo how to insert struct in vector
7  Release     : 08/01/2008 1.0
8  */

10 #include <iostream>
11 #include <vector>
12 #include <string>
13 
14 using namespace std;
15  
16 struct Student {
17   int  id;
18   string name;
19 };
20  
21 int main() {
22   vector<struct Student> svec;
23  
24   struct Student master;
25   master.id = 1;
26   master.name = "clare";
27   svec.push_back(master);
28  
29   master.id = 2;
30   master.name = "jingyi";
31   svec.push_back(master);
32  
33   master.id = 3;
34   master.name = "jessie";
35   svec.push_back(master);
36  
37   vector<struct Student>::iterator iter = svec.begin();
38   for(iter; iter != svec.end(); ++iter)
39     cout << iter->id << " " << iter->name << endl;
40 }

執行結果

1 clare
2 jingyi
3 jessie

由於vector內放的是struct,所以push_back()要塞個也是struct,而不能針對struct的member來塞。因此要先宣告一個暫存的struct做中介。

以上的code,看起來都是push_back()同一個master object,這樣沒有問題嗎?因為push_back()進vector是採用copy的方式,會產生一個新的副本,所以才可以這樣使用。

Conclusion
或許你會覺得這樣子很蠢,還要產生一個中介的struct,以目前的C++與STL來說就只能這樣做,在boost與C++ 0x都另外提供了tuple,這樣就不需要struct,有興趣者請參閱The Boost Tuple Library。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.