官方解釋:
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
- empty
- size
- back
- push_back
- pop_back
The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used.
常用成員函數:
- empty :Test whether container is empty (public member function )
- size:Return size (public member function )
- top:Access next element (public member function )
- push:Insert element (public member function )
- emplace :Construct and insert element (public member function )
- pop:Remove top element (public member function )
- swap :Swap contents (public member function )
emplace代碼實現:
// stack::emplace #include <iostream> // std::cin, std::cout #include <stack> // std::stack #include <string> // std::string, std::getline(string) int main () { std::stack<std::string> mystack; mystack.emplace ("First sentence"); mystack.emplace ("Second sentence"); std::cout << "mystack contains:\n"; while (!mystack.empty()) { std::cout << mystack.top() << '\n'; mystack.pop(); } return 0; }
結果:
mystack contains: Second sentence First sentence
swap代碼實現:
1 // stack::swap 2 #include <iostream> // std::cout 3 #include <stack> // std::stack 4 5 int main () 6 { 7 std::stack<int> foo,bar; 8 foo.push (10); foo.push(20); foo.push(30); 9 bar.push (111); bar.push(222); 10 11 foo.swap(bar); 12 13 std::cout << "size of foo: " << foo.size() << '\n'; 14 std::cout << "size of bar: " << bar.size() << '\n'; 15 16 return 0; 17 }
結果:
size of foo: 2 size of bar: 3
一些思考:emplace跟插入有什么區別呢?
當調用push或insert成員函數時,我們將元素類型的對象傳遞給它們,這些對象被拷貝到容器中。而當我們調用一個emplace成員函數時,則是將參數傳遞給元素類型的構造函數。emplace成員使用這些參數在容器管理的內存空間中直接構造元素。
emplace函數的參數根據元素類型而變化,參數必須與元素類型的構造函數相匹配。emplace函數在容器中直接構造元素。傳遞給emplace函數的參數必須與元素類型的構造函數相匹配。
參考:https://blog.csdn.net/fengbingchun/article/details/78670376
