2014-04-18 107 views
0

如推回使用存儲變量 書(書名,作者,ISBN)有沒有辦法push_back多個變量到for循環中的向量?

vector <Book> books; 
Book book1("a", "Jim John", 1000); 
Book book2("b", "Jim John", 1001); 
Book book3("c", "Billy Bill", 1002); 
Book book4("d", "Greg Lumburge", 1003); 
Book book5("e", "Dallas Orange", 1004); 
Book book6("f", "Old McDonald", 1005); 

books.push_back(book1); 
books.push_back(book2); 
books.push_back(book3); 
books.push_back(book4); 
books.push_back(book5); 
books.push_back(book6); 

回答

2

與支持C++ 11標準的編譯器可以使用emplace_back,像這樣:

vector <Book> books; 
books.emplace_back("a", "Jim John", 1000); 
books.emplace_back("b", "Jim John", 1001); 
books.emplace_back("c", "Billy Bill", 1002); 
books.emplace_back("d", "Greg Lumburge", 1003); 
books.emplace_back("e", "Dallas Orange", 1004); 
books.emplace_back("f", "Old McDonald", 1005); 

但還是比較容易,用C++ 11,是剛剛升北京時間所有的數據在一個大括號初始化:

vector <Book> books = 
{ 
    {"a", "Jim John", 1000}, 
    {"b", "Jim John", 1001}, 
    {"c", "Billy Bill", 1002}, 
    {"d", "Greg Lumburge", 1003}, 
    {"e", "Dallas Orange", 1004}, 
    {"f", "Old McDonald", 1005} 
}; 

然後可以很容易地添加const,如果合適的話。


在C++ 03你可以這樣做,而不是:

static Book const data[] = 
{ 
    Book("a", "Jim John", 1000), 
    Book("b", "Jim John", 1001), 
    Book("c", "Billy Bill", 1002), 
    Book("d", "Greg Lumburge", 1003), 
    Book("e", "Dallas Orange", 1004), 
    Book("f", "Old McDonald", 1005) 
}; 
int const data_size = sizeof(data)/sizeof(*data); 

vector <Book> books(data, data + data_size); 
0

如果你可以使用C++ 11,那麼你可以使用一個初始化列表:

vector<Book> books = { 
    {"a", "Jim John", 1000}, 
    {"b", "Jim John", 1001}, 
    {"c", "Billy Bill", 1002}, 
    {"d", "Greg Lumburge", 1003}, 
    {"e", "Dallas Orange", 1004}, 
    {"f", "Old McDonald", 1005}, 
};