STL库相关练习代码

第一题:

#include <iostream>
#include <vector>
#include <iterator>
#include <string>


using namespace std;

bool huiwen(string input);



int main()
{
    string input;
    cout<<"请输入你的字符串\n"<<endl;
    getline(cin,input);
    if(huiwen(input))
    {
        cout<<"是回文\n";
    }
    else
    {
        cout<<"不是回文\n";
    }
}


bool huiwen(string input)
{
    string::iterator forware=input.begin();
    string::reverse_iterator backware=input.rbegin();
    int input_length=input.length();
    for(int i=0;i<input_length/2;i++)
    {
        if(*forware==*backware)
        {
            forware++;
            backware++;
        }
        else
        {
            return false;
        }
        return true;
    }
}



第二题
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <string>


using namespace std;


bool huiwen(string input);


int main()
{
    string input;
    cout<<"请输入你的字符串\n";
    getline(cin,input);
    string::iterator it;
    for(it=input.begin();it!=input.end();)
    {
        if(isalpha(*it))
        {
            it=input.erase(it);
            continue;
        }
        else
        {
            *it=tolower(*it);
            it++;
        }
    }
    if(huiwen(input))
    {
        cout<<"为回文\n";
    }
    else
    {
        cout<<"不是回文\n";
    }
}




bool huiwen(string input)
{
    string::iterator forware=input.begin();
    string::reverse_iterator backware=input.rbegin();
    int input_length=input.length();
    for(int i=0;i<input_length/2;i++)
    {
        if(*forware==*backware)
        {
            forware++;
            backware++;
        }
        else
        {
            return false;
        }
        return true;
    }
}

第三题

#include <iostream>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <iterator>
#include <vector>
#include <fstream>
#include <ctime>
#include <list>
#include <queue>
#include <memory>
using std::string;
using namespace std;
const string Filename="word.txt";

int main()
{
    using std::cout;
    using std::cin;
    using std::tolower;
    using std::endl;
    vector<string> wordlist;
    ifstream in;
    in.open(Filename.c_str());
    string inword;

    while(in>>inword)
    {
        wordlist.push_back(inword);
    }

    std::srand(std::time(0));
    char play;
    cout << "Will you play a word game? <y/n> ";
    cin >> play;
    play = tolower(play);
    while (play == 'y')
    {
        string target = wordlist[std::rand() % wordlist.size()];
        int length = target.length();
        string attempt(length, '-');
        string badchars;
        int guesses = 6;
        cout << "Guess my secret word. It has " << length
            << " letters, and you guess\n"
            << "one letter at a time. You get " << guesses
        << " wrong guesses.\n";
    cout << "Your word: " << attempt << endl;
    while (guesses > 0 && attempt != target)
    {
        char letter;
        cout << "Guess a letter: ";
        cin >> letter;
        if (badchars.find(letter) != string::npos
            || attempt.find(letter) != string::npos)
        {
            cout << "You already guessed that. Try again.\n";
                continue;
        }
        int loc = target.find(letter);
        if (loc == string::npos)
        {
            cout << "Oh, bad guess!\n";
            --guesses;
            badchars += letter; // add to string
        }
        else
        {
            cout << "Good guess!\n";
            attempt[loc]=letter;
            // check if letter appears again
            loc = target.find(letter, loc + 1);
            while (loc != string::npos)
            {
                attempt[loc]=letter;
                loc = target.find(letter, loc + 1);
            }
        }
        cout << "Your word: " << attempt << endl;
        if (attempt != target)
        {
            if (badchars.length() > 0)
                cout << "Bad choices: " << badchars << endl;
            cout << guesses << " bad guesses left\n";
        }
    }
    if (guesses > 0)
        cout << "That's right!\n";
    else
        cout << "Sorry, the word is " << target << ".\n";
        cout << "Will you play another? <y/n> ";
        cin >> play;
        play = tolower(play);
    }

    cout << "Bye\n";

    return 0;
}

 第四题 

 

#include <iostream>
#include <stdlib.h>
#include <list>
#include <algorithm>



int reduce(long qr[],int n);

using namespace std;

int main()
{
    long ar[] = { 12, 2, 13, 12, 2, 55, 32, 44, 32, 100, 32, 12 };
    int length_old=12;
    int length_new;
    cout<<"开始输出原始数据\n"<<endl;
    for(int i=0;i<length_old;i++)
    {
        cout<<ar[i]<<' ';
    }
    cout<<endl;
    length_new=reduce(ar,length_old);
    cout<<"开始输出新的字符串"<<endl;
    for(int i=0;i<length_new;i++)
    {
        cout<<ar[i]<<' ';
    }

    
}
int reduce(long qr[],int n)
{
    list<long> la(qr,qr+n); 
    la.sort();
    la.unique();
  
    int len=0;
    for(list<long>::iterator it=la.begin();it!=la.end();it++)
    {
        *(qr+len)=*it;
        len++;
    }
    for(int i=len;i<n;i++)
    {
        *(qr+len)=0;
    }
    return len;
}

 

第六题

#include <iostream>
#include <stdlib.h>
#include <list>
#include <algorithm>

using namespace std;
template<class T>
int reduce(T qr[],int n);



int main()
{
    long ar[] = { 12, 2, 13, 12, 2, 55, 32, 44, 32, 100, 32, 12 };
    int length_old=12;
    int length_new;
    cout<<"开始输出原始数据\n"<<endl;
    for(int i=0;i<length_old;i++)
    {
        cout<<ar[i]<<' ';
    }
    cout<<endl;
    length_new=reduce(ar,length_old);
    cout<<"开始输出新的字符串"<<endl;
    for(int i=0;i<length_new;i++)
    {
        cout<<ar[i]<<' ';
    }

    
}
template<class T>
int reduce(T qr[],int n)
{
    list<T> la(qr,qr+n); 
    la.sort();
    la.unique();
  
    int len=0;
    for(typename list<T>::iterator it=la.begin();it!=la.end();it++)
    {
        *(qr+len)=*it;
        len++;
    }
    for(int i=len;i<n;i++)
    {
        *(qr+len)=0;
    }
    return len;
}

第6题

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
#include <queue>


class Customer
{
private:
    long arrive;     // arrival time for customer
    int processtime; // processing time for customer
public:
    Customer() { arrive = processtime = 0; }
    void set(long when);
    long when() const { return arrive; }
    int ptime() const { return processtime; }
};
void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when;
}


const int MIN_PER_HR = 60;

bool newcustomer(double x);      // is there a new customer?

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
// setting things up
    std::srand(std::time(0));    // random initializing of rand()

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;
    std::queue<Customer> line;              // line queue holds up to qs people

    cout << "Enter the number of simulation hours: ";
    int hours;                   // hours of simulation
    cin >> hours;
    // simulation will run 1 cycle per minute
    long cyclelimit = MIN_PER_HR * hours; // # of cycles

    cout << "Enter the average number of customers per hour: ";
    double perhour;      // average # of arrival per hour
    cin >> perhour;
    double min_per_cust; // average time between arrivals
    min_per_cust = MIN_PER_HR / perhour;

    Customer temp;           // new customer data
    long turnaways = 0;  // turned away by full queue
    long customers = 0;  // joined the queue
    long served = 0;     // served during the simulation
    long sum_line = 0;   // cumulative line length
    int wait_time = 0;   // time until autoteller is free
    long line_wait = 0;  // cumulative time in line

// running the simulation
    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust)) // have newcomer
        {
            if (qs==line.size())
                turnaways++;
            else
            {
                customers++;
                temp.set(cycle);    // cycle = time of arrival
                line.push(temp); // add newcomer to line
            }
        }
        if (wait_time <= 0 && !line.empty())
        {
            temp=line.front();      // attend next customer
            wait_time = temp.ptime(); // for wait_time minutes
            line_wait += cycle - temp.when();
            served++;
        }
        if (wait_time > 0)
            wait_time--;
        sum_line += line.size();
    }

// reporting results
    if (customers > 0)
    {
        cout << "customers accepted: " << customers << endl;
        cout << " customers served: " << served << endl;
        cout << " turnaways: " << turnaways << endl;
        cout << "average queue size: ";
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout << (double) sum_line / cyclelimit << endl;
        cout << " average wait time: "
             << (double) line_wait / served << " minutes\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";

    return 0;
}

// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1);
}

第七题

#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
using namespace std;
vector<int> Lotto(int total,int choice);

int main()
{
    srand(time(0));
    vector<int>winners;
    winners=Lotto(51,6);
    for(int i=0;i<6;i++)
    {
        cout<<winners[i]<<' ';;
    }
    cout<<endl;
    return 0;
}


vector<int> Lotto(int total,int choice)
{
    vector<int> car(total);
    for(int i=0;i<total;i++)
    {
        car[i]=i+1;
    }
    random_shuffle(car.begin(),car.end());
    vector<int> cars(choice);
    for(int i=0;i<choice;i++)
    {
        cars[i]=car[i];
    }
    sort(cars.begin(),cars.end());
    return cars;
}

第八题

#include <iostream>
#include <vector>
#include <cstring>
#include <set>
#include <iterator>
#include <algorithm>
using namespace std;

set<string> Input_name();





int main()
{
    set<string> M_f_n;
    set<string> P_f_n;
    set<string> U_f_n;
    cout<<"开始输入Mat朋友的姓名\n";
    M_f_n=Input_name();
    copy(M_f_n.begin(), M_f_n.end(), ostream_iterator<string, char>(cout, " "));
    cout<<endl;
    cout<<"开始输入Pat朋友的姓名\n";
    P_f_n=Input_name();
    copy(P_f_n.begin(), P_f_n.end(), ostream_iterator<string, char>(cout, " "));
    cout<<endl;
    set_union(M_f_n.begin(),M_f_n.end(),P_f_n.begin(),P_f_n.end(),insert_iterator<set<string>>(U_f_n,U_f_n.begin()));
    cout<<"开始输出并集\n"<<endl;
    copy(U_f_n.begin(), U_f_n.end(), ostream_iterator<string, char>(cout, " "));
    cout<<endl;
}

set<string> Input_name()
{
    set<string> name;
    string name_f;
    while(cin>>name_f)
    {
        name.insert(name_f);
        if(cin.get()=='\n')
        {
            break;
        }
    }
    return name;
}

第10题

#include <iostream>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <iterator>
#include <vector>
#include <fstream>
#include <ctime>
#include <list>
#include <queue>
#include <memory>


using namespace std;



struct Review
{
    string title;
    int rating;
    double price;
};
bool FillRevice(Review & rr)
{
    cout << "Enter book title (quit to quit): ";
    getline(cin, rr.title);
    if (rr.title == "quit")
    {
        return false;
    }
    cout << "Enter book rating: ";
    cin >> rr.rating;
    if (!cin)
    {
        return false;
    }

    cout << "Enter book price: ";
    cin >> rr.price;
    if (!cin)
    {
        return false;
    }
    while (cin.get() != '\n')
        continue;

    return true;
}
void ShowReview(const shared_ptr<Review> & rr)
{
    cout << rr->rating << "\t" << rr->title << "\t" << rr->price << endl;
}
bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
    if (r1->title < r2->title)
    {
        return true;
    }
    else if (r1->title == r2->title && r1->rating < r2->rating)
        return true;
    else
        return false;
}
bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
    if (r1->rating < r2->rating)
        return true;
    else
        return false;
}
bool betterThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
    if (r1->rating > r2->rating)
        return true;
    else
        return false;
}
bool expensiveThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
    if (r1->price > r2->price)
        return true;
    else
        return false;
}
bool cheaperThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
    if (r1->price < r2->price)
        return true;
    else
        return false;
}
void p16_10(void)
{
    vector<shared_ptr<Review> > books;
    Review temp;
    while (FillRevice(temp))
    {
        shared_ptr<Review> in(new Review(temp));
        books.push_back(in);
    }
    cout << "Enter your choice: " << endl;
    cout << "0:按原始顺序显示, 1:按字母表顺序显示, 2:按评级升序显示" << endl;
    cout << "3:按评级降序显示, 4:按价格升序显示  , 5:按价格降序显示" << endl;
    cout << "6:退出" << endl;
    int choice = 0;
    vector<shared_ptr<Review> > original_books(books.begin(), books.end());
    while (cin >> choice && choice != 6)
    {
        switch (choice)
        {
        case 0:
            copy(original_books.begin(), original_books.end(), books.begin());
            break;

        case 1:
            sort(books.begin(), books.end());
            break;

        case 2:
            sort(books.begin(), books.end(), worseThan);
            break;

        case 3:
            sort(books.begin(), books.end(), betterThan);
            break;

        case 4:
            sort(books.begin(), books.end(), cheaperThan);
            break;

        case 5:
            sort(books.begin(), books.end(), expensiveThan);
            break;

        default:
            break;
        }

        for_each(books.begin(), books.end(), ShowReview);
    }

    return;
}




int main(int argc, char ** argv)
{
    p16_10();

    while (cin.get());

    return 0;
}

 

posted @ 2022-10-16 20:27  术术子  阅读(24)  评论(0编辑  收藏  举报