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.
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有