std::list<std::string> names {"Jane","Jim", "Jules", "Janet"}; names.emplace_back("Ann"); std::string name("Alan"); names.emplace_back(std::move(name)); names.emplace_front("Hugo"); names.emplace(++begin(names), "Hannah"); for(const auto& name : names) std::cout << name << std::endl;迴圈變數 name 是依次指向每個 list 元素的參照,使得迴圈能夠逐行輸出各個字串。下面通過一個練習檢驗一下前面學到的知識。這個練習讀取通過鍵盤輸入的讀語並將它們儲存到一個 list 容器中:
// Working with a list #include <iostream> #include <list> #include <string> #include <functional> using std::list; using std::string; // List a range of elements template<typename Iter> void list_elements(Iter begin, Iter end) { while (begin != end) std::cout << *begin++ << std::endl; } int main() { std::list<string> proverbs; // Read the proverbs std::cout << "Enter a few proverbs and enter an empty line to end:" << std::endl; string proverb; while (getline(std::cin, proverb, 'n'), !proverb.empty()) proverbs.push_front(proverb); std::cout << "Go on, just one more:" << std::endl; getline(std::cin, proverb, 'n'); proverbs.emplace_back(proverb); std::cout << "The elements in the list in reverse order are:" << std::endl; list_elements(std::rbegin(proverbs), std::rend(proverbs)); proverbs.sort(); // Sort the proverbs in ascending sequence std::cout << "nYour proverbs in ascending sequence are:" << std::endl; list_elements(std::begin(proverbs), std::end(proverbs)); proverbs.sort(std::greater<>()); // Sort the proverbs in descending sequence std::cout << "nYour proverbs in descending sequence:" << std::endl; list_elements(std::begin(proverbs), std::end(proverbs)); }執行結果為:
Enter a few proverbs and enter an empty line to end: A nod is a good as a wink to a blind horse.
Many a mickle makes a muckle.
A wise man stands on the hole in his carpet.
Least said, soonest mended.
Go on, just one more:
A rolling stone gathers no moss.
The elements in the list in reverse order are:
A rolling stone gathers no moss.
A nod is a good as a wink to a blind horse.
Many a mickle makes a muckle.
A wise man stands on the hole in his carpet.
Least said, soonest mended.
Your proverbs in ascending sequence are:
A nod is a good as a wink to a blind horse.
A rolling stone gathers no moss.
A wise man stands on the hole in his carpet.
Least said, soonest mended.
Many a mickle makes a muckle.
Your proverbs in descending sequence:
Many a mickle makes a muckle.
Least said, soonest mended.
A wise man stands on the hole in his carpet.
A rolling stone gathers no moss.
A nod is a good as a wink to a blind horse.