• 快速或安全的访问std::vector实例的方法, std::vector的插入排序


    在这里插入图片描述
    在这里插入图片描述

    快速或安全的访问std::vector实例的方法

    std::vector可能是STL容器中适用范围最广的,因为其存储数据的方式和数组一样,并且还有相对完善的配套设施。不过,非法访问一个vector实例还是十分危险的。如果一个vector实例具有100个元素,那当我们想要访问索引为123的元素时,程序就会崩溃掉。如果不崩溃,那么你就麻烦了,未定义的行为会导致一系列奇奇怪怪的错误,查都不好查。经验丰富的开发者会在访问前,对索引进行检查。这样的检查其实比较多余,因为很多人不知道std::vector有内置的检查机制。

    How to do it…

    本节我们将使用两种不同的方式访问一个std::vector实例,并且利用其特性编写更加安全的代码。

    1. 先包含相应的头文件,并且用1000个123填满一个vector实例:
    #include 
    #include 
    using namespace std;
    int main()
    {
        const size_t container_size{1000};
        vector v(container_size, 123);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 我们通过[]操作符访问范围之外的元素:
        cout << "Out of range element value: "
             << v[container_size + 10] << '\n';
    
    • 1
    • 2
    1. 之后我们使用at函数访问范围之外的元素:
        cout << "Out of range element value: "
             << v.at(container_size + 10) << '\n';
    }
    
    • 1
    • 2
    • 3
    1. 让我们运行程序,看下会发生什么。下面的错误信息是由GCC给出。其他编译器也会通过不同方式给出类似的错误提示。第一种方式得到的结果比较奇怪。超出范围的访问方式并没有让程序崩溃,但是访问到了与123相差很大的数字。第二种方式中,我们看不到打印出来的结果,因为在打印之前程序已经崩溃了。当越界访问发生的时候,我们可以通过异常的方式更早的得知!
    Out of range element value: -726629391
    terminate called after throwing an instance of 'std::out_of_range'
    what(): array::at: __n (which is 1010) >= _Nm (which is 1000)
    Aborted (core dumped)
    
    • 1
    • 2
    • 3
    • 4

    How it works…

    std::vector提供了[]操作符和at函数,它们的作用几乎是一样的。at函数会检查给定的索引值是否越界,如果越界则返回一个异常。这对于很多情景都十分适用,不过因为检查越界要花费一些时间,所以at函数会让程序慢一些。

    当需要非常快的索引成员时,并能保证索引不越界,我们会使用[]快速访问vector实例。很多情况下,at函数在牺牲一点性能的基础上,有助于发现程序内在的bug。

    Note:

    默认使用at函数是一个好习惯。当代码的性能很差,但没有bug存在时,可以使用性能更高的操作符来替代at函数。

    There’s more…

    当然,我们需要处理越界访问,避免整个程序崩溃。为了对越界访问进行处理,我们可以使用截获异常的方式。可以用try代码块将调用at函数的部分包围,并且定义错误处理的catch代码段。

    try {
        std::cout << "Out of range element value: "
                  << v.at(container_size + 10) << '\n';
    } catch (const std::out_of_range &e) {
        std::cout << "Ooops, out of range access detected: "
                  << e.what() << '\n';
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Note:

    顺带一提,std::array也提供了at函数。

    保持对std::vector实例的排序

    arrayvector不会对他们所承载的对象进行排序。有时我们去需要排序,但这不代表着我们总是要去切换数据结构,需要排序能够自动完成。在我们的例子有如有一个std::vector实例,将添加元素后的实例依旧保持排序,会是一项十分有用的功能。

    How to do it…

    本节中我们使用随机单词对std::vector进行填充,然后对它进行排序。并在插入更多的单词的同时,保证vector实例中单词的整体排序。

    1. 先包含必要的头文件。
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 声明所要使用的命名空间。
    using namespace std;
    
    • 1
    1. 完成主函数,使用一些随机单词填充vector实例。
    int main()
    {
        vector v {"some", "random", "words",
                          "without", "order", "aaa",
                          "yyy"};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 对vector实例进行排序。我们使用一些断言语句和STL中自带的is_sorted函数对是否排序进行检查。
        assert(false == is_sorted(begin(v), end(v)));
        sort(begin(v), end(v));
        assert(true == is_sorted(begin(v), end(v)));
    
    • 1
    • 2
    • 3
    1. 这里我们使用insert_sorted函数添加随机单词到已排序的vector中,这个函数我们会在后面实现。这些新插入的单词应该在正确的位置上,并且vector实例需要保持已排序的状态。
        insert_sorted(v, "foobar");
        insert_sorted(v, "zzz");
    
    • 1
    • 2
    1. 现在,我们来实现insert_sorted函数。
    void insert_sorted(vector &v, const string &word)
    {
        const auto insert_pos (lower_bound(begin(v), end(v), word));
        v.insert(insert_pos, word);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 回到主函数中,我们将vector实例中的元素进行打印。
        for (const auto &w : v) {
            cout << w << " ";
        }
        cout << '\n';
    }    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 编译并运行后,我们得到如下已排序的输出。
    aaa foobar order random some without words yyy zzz
    
    • 1

    How it works…

    程序整个过程都是围绕insert_sorted展开,这也就是本节所要说明的:对于任意的新字符串,通过计算其所在位置,然后进行插入,从而保证vector整体的排序性。不过,这里我们假设的情况是,在插入之前,vector已经排序。否则,这种方法无法工作。

    这里我们使用STL中的lower_bound对新单词进行定位,其可接收三个参数。头两个参数是容器开始和结尾的迭代器。这确定了我们单词vector的范围。第三个参数是一个单词,也就是要被插入的那个。函数将会找到大于或等于第三个参数的首个位置,然后返回指向这个位置的迭代器。

    获取了正确的位置,那就使用vector的成员函数insert将对应的单词插入到正确的位置上。

    There’s more…

    insert_sorted函数很通用。如果需要其适应不同类型的参数,这样改函数就能处理其他容器所承载的类型,甚至是容器的类似,比如std::setstd::dequestd::list等等。(这里需要注意的是成员函数lower_boundstd::lower_bound等价,不过成员函数的方式会更加高效,因为其只用于对应的数据集合)

    template 
    void insert_sorted(C &v, const T &item)
    {
        const auto insert_pos (lower_bound(begin(v), end(v), item));
        v.insert(insert_pos, item);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    当我们要将std::vector类型转换为其他类型时,需要注意的是并不是所有容器都支持std::sort。该函数所对应的算法需要容器为可随机访问容器,例如std::list就无法进行排序。

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include  // for ostream_iterator
    #include 
    
    using namespace std;
    
    template <typename C>
    void print_vector(const C &v)
    {
        std::cout << "Words: {";
        copy(begin(v), end(v), ostream_iterator<typename C::value_type>(cout, " "));
        std::cout << "}\n";
    }
    
    template <typename C, typename T>
    void insert_sorted(C &v, const T &word)
    {
        const auto it (lower_bound(begin(v), end(v), word));
        v.insert(it, word);
    }
    
    int main()
    {
        list<string> v {"some", "random", "words", "without", "order", "aaa", "yyy"};
    
        // assert(false == is_sorted(begin(v), end(v)));
    
        print_vector(v);
    
        //sort(begin(v), end(v));
    
        //assert(true == is_sorted(begin(v), end(v)));
    
        print_vector(v);
    
        insert_sorted(v, "foobar");
        insert_sorted(v, "yzz");
        insert_sorted(v, "zzz");
    
        print_vector(v);
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    在这里插入图片描述

  • 相关阅读:
    java中Runnable、Callable、Future、RunnableFuture、CompletionStage接口区别
    C# 之委托和事件
    EasyExcel入门使用教程
    Dubbo(分布式框架·上)
    Linux 驱动的内核适配 - 方法
    40_ue4进阶末日生存游戏开发[添加和删除内容]
    HTML创建文本框的三种方式
    数字IC设计笔试题汇总(一)
    CICD 持续集成与持续交付——jenkins
    VEX —— Functions|Transforms and Space
  • 原文地址:https://blog.csdn.net/weixin_42244181/article/details/127604077