(原創) 如何將struct塞進vector? (C/C++) (STL)
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 */
9
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 }
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 */
9
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
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。
See Also
(原創) 如何將struct array寫入文字檔? 如何從文字檔讀出struct array? (C/C++) (C)
The Boost Tuple Library