STL(标准模板库)02

2023-11-02 09:23:09 浏览数 (1)

有了上节笔记的基础,本篇我们就可以写一些例子来巩固知识 我们用动态数组vector编写一个书架,这个书架可以上架图书和浏览图书

代码语言:javascript复制
#include<iostream>
#include<vector>
#include<string>
struct Riview {
    std::string title;
    int rating;
};
bool FillReview(Riview& rv);
void Show(const Riview& rr);
int main()
{
    using std::cout;
    using std::vector;
    vector<Riview> Books;
    Riview temp;
    while (FillReview(temp))
    {
        Books.push_back(temp);
    }
    int num = Books.size();
    for (size_t i = 0; i < num; i  )
    {
        Show(Books[i]);
    }
    cout << "Reprising:n"
        << "RatingtBookn";
    vector<Riview>::iterator pd;
    for (pd = Books.begin(); pd != Books.end(); pd  )
    {
        Show(*pd);
    }
    vector<Riview> oldlist(Books);
    if (num>3)
    {
        Books.erase(Books.begin()   1, Books.begin()   3);
        cout << "删除第二个图书到第3个图书后.n";
        for (pd = Books.begin(); pd!=Books.end(); pd  )
        {
            Show(*pd);
        }
        Books.swap(oldlist);
        cout << "交换两个书架的容器数据后.n";
        for (pd = Books.begin(); pd != Books.end(); pd  )
        {
            Show(*pd);
        }

    }
    else
    {
        cout << "error.n";
    }
    return 0;
}

bool FillReview(Riview& rv)
{
    std::cout << "请输入你书籍的名字: ";
    std::getline(std::cin, rv.title);
    if (rv.title == "quit")
    {
        return false;
    }
    std::cout << "请输入图书编号: ";
    std::cin >> rv.rating;
    if (!std::cin)
    {
        return false;
    }
    while (std::cin.get()!='n')
    {
        continue;
    }
    return true;
}

void Show(const Riview& rr)
{
    std::cout << rr.rating << 't' << rr.title << std::endl;
}

Q:定义一个 int 类型的 vector 动态数组,将以下元素:1, 4, 3, 7, 9, 3, 6, 8, 3, 5, 2, 3, 7 插入到动态数组中。之后,使用 for 循环删除动态数组中的值为 3 的元素,并将结果输出出来!

代码语言:javascript复制
#include<vector>
#include<iostream>
int main()
{
    using std::vector;
    int arr[] = { 1, 4, 3, 7, 9, 3, 6, 8, 3, 5, 2, 3, 7 };
    vector<int> arr_int(arr, arr   sizeof(arr) / sizeof(int));
    vector<int>::iterator pr;
    for (pr = arr_int.begin(); pr!=arr_int.end(); pr  )
    {
        if (*pr == 3)
        {
            pr = arr_int.erase(pr);
        }
    }
    int num = arr_int.size();
    std::cout << "arr_int = ";
    for (int i = 0; i < num; i  )
    {
         std::cout<< 't' << arr_int[i];
    }

}

0 人点赞