《C++ STL编程实战》读书笔记(三)

容器适配器是一个封装了序列容器的模板

(1)stack是一个封装了deque容器的适配器模板

(2)queue是一个封装了deque容器的适配器模板

(3)priority_queue是一个封装了vector容器的适配器模板

//ex3_01
//2019年9月30日16:50:27

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

inline size_t precedence(const char op)
{
    if (op == '+' || op =='-')
        return 1;
    if (op == '*' || op =='/')
        return 2;
    if (op == '^')
        return 3;
    throw runtime_error {string{"invalid operator:"} + op};
}

double execute(stack& ops, stack& operands)
{
    double result {};

    double rhs {operands.top()};
    operands.pop();
    double lhs {operands.top()};
    operands.pop();

    switch (ops.top())
    {
    case '+':
        result = lhs + rhs;
        break;
    case '-':
        result = lhs - rhs;
        break;
    case '*':
        result = lhs * rhs;
        break;
    case '/':
        result = lhs / rhs;
        break;
    case '^':
        result = pow(lhs,rhs);
        break;
    default:
        throw runtime_error {string{"invalid operator:"} + ops.top()};
    }
    ops.pop();
    operands.push(result);
    return result;
}


int main()
{
    stack operands;
    stack operators;
    string exp;
    cout<<"An arithemtic expression can include the operators +,-,*,/"
        <<" and ^ for exponentiation" <
//ex3_03
//exercising a priority queue container adapter
//2019年9月30日19:59:35

#include 
#include 
#include 

using namespace std;

template
void list_pq(priority_queuepq, size_t count = 5)
{
    size_t n{count};
    while(! pq.empty())
    {
        cout<words;
    string word;
    cout<<"Enter words separated by spaces, enter Ctrl +Z on a separate line to end."<>word).eof())
            break;
        words.push(word);
    }

    cout<<" You have entered "<< words.size() <<" words."<
//ex3_04
//using a heap as a priority_queue
//2019年9月30日20:48:56

#include 
#include 
#include 
#include 
#include 

using namespace std;

//list a deque of words
void show(deque& words, size_t count=5)
{
    if(words.empty())
        return;
    auto max_len = max_element(begin(words),end(words),[](const string& s1, const string& s2){return s1.size()size();

    //output the words
    size_t n{count};
    for(const auto&word:words)
    {
        cout<< setw(max_len+1)<words;
    string word;
    cout<<"Enter the words separated by spaces, enter Ctrl+Z to end";

    while(true)
    {
        if((cin>>word).eof())
        {
            cin.clear();
            break;
        }
        words.push_back(word);
    }

    cout<<"The words in the list are:"<>word).eof())
        {
            cin.clear();
            break;
        }
        words.push_back(word);
        push_heap(begin(words),end(words));
    }
    cout<<"The words in the list are now:"<

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(C++,STL,学习笔记)