Re: [問題] 動態產生物件

看板C_and_CPP (C/C++)作者 ( )時間16年前 (2009/08/16 15:49), 編輯推噓2(202)
留言4則, 3人參與, 最新討論串3/3 (看更多)
可以直接用 vector 搞定, 就直接把 cin 讀進來的值拿去造出物件再 push_back 進去, 類似這樣寫: vector<person> v; cin >> input; v.push_back(person(input)); 以往 vector 會被排斥的一大原因就是它初值很難送, 如果是需要放一些預設的物件進去時大都要先造個傳統 array 再 copy 進去, 結果很多人就乾脆直接使用傳統 array, 但是這情況現在已經差不多可以翻盤了。 新時代新寫法, GCC 4.4.0 以上支援, VS 2010 不知道有沒有。 #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace boost::lambda; using namespace std; class Person { public: Person(const string &name) : name_(name) { } string name() const { return name_; } private: string name_; }; int main() { vector<Person> v{ Person("a"), Person("b"), Person("c") }; for_each(v.begin(), v.end(), cout << bind(&Person::name, _1) << " "); cout << endl; return 0; } 編譯: > g++ -std=gnu++0x init.cxx -o init 執行: > ./init a b c 初值的部分可以直接像 main() 第一行那樣送, 有 constructor 也沒有關係, 事後想補元素進去也是老方法用 push_back(), 譬如 v.push_back(Person("d")), 如果你是想要完全由 cin 決定那就不需要新寫法, 一個一個 push_back 就可以了。 如果是想要一次插入多筆資料到最後面的話, 可以寫: v.insert(v.end(), { Person("d"), Person("e") }); -- Ling-hua Tseng (uranus@tinlans.org) Department of Computer Science, National Tsing-Hua University Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design Researching: Software pipelining for VLIW architectures Homepage: https://www.tinlans.org -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.160.119.123 ※ 編輯: tinlans 來自: 118.160.119.123 (08/16 16:26)

08/16 20:02, , 1F
恭喜原po的Lab今年ES競賽open source組拿second prize
08/16 20:02, 1F

08/16 20:11, , 2F
VS2010和icc11應該都有lambda了
08/16 20:11, 2F

08/17 03:03, , 3F
新寫法是指 std::initializer_list 跟 compiler 的搭配。
08/17 03:03, 3F

08/17 03:03, , 4F
container 實作對應的 ctor 就能像上面那樣初始化。
08/17 03:03, 4F
文章代碼(AID): #1AXxeHKP (C_and_CPP)
文章代碼(AID): #1AXxeHKP (C_and_CPP)