[GeekBand] STL vector 查找拷贝操做效率分析

本文参考文献::GeekBand课堂内容,授课老师:张文杰html

            :C++ Primer 11 中文版(第五版)ios

                   :网络资料: 叶卡同窗的部落格  http://www.leavesite.com/算法

                                                             http://blog.sina.com.cn/s/blog_a2a6dd380102w73e.htmlwindows

 

1、关于Vector的基本概念及相关算法简介

一、什么是vector?数组

  简单的理解:数组!网络

     进一步的理解:变长一维的动态数组,连续存放的内存块,堆内分配内存。支持[]操做(一会就会用到),支持下标操做。数据结构

     再进一步的理解:vector表示对象的集合,集合中每一个对象都有与之对应的索引(理解为下标,这里能够保存不少元素的对象,包括不限于,如int string、或者本身定义的类的对象等等。app

 

二、Vector的初始化less

有几种基本初始化方法:函数

vector<T> v1 ;          //构造函数
vector<T> v2(v1) ;    //拷贝构造函数
vector<T> v2 =v1 ;   //拷贝赋值
vector<T> v1{ 0, 0, 30, 20, 0, 0, 0, 0, 10, 0 };   //初始化

 本文中采用最基本的方法进行初始化。

三、Vector基本操做

vector<int>  vec;
vector<int> vec2;
vec.push_back(t);  //向v的尾端添加元素t
vec.empty();
vec.size();
vec == vec2;  //相等相似的操做都有

4、迭代器

简单的理解:相似于指针。以下面的一句话,迭代器有一个优势,那就是全部的标准库容器均可以使用迭代器,具备极强的通用性。

 

vector<int>::iterator result = find_if(Vec1.begin(), Vec1.end(), bind2nd(not_equal_to<int>(), unexpectedInt));

 

5、本文中可能会用到的一些(算法)操做:

一、函数 :not_equal_to,重载了操做符(),判断左右两个数是否相等,不等返回值 TRUE、即1,相等返回 FALSE、即0.

    相似的函数有equal_to 

template<class _Ty = void>
    struct not_equal_to
        : public binary_function<_Ty, _Ty, bool>
    {    // functor for operator!=
    bool operator()(const _Ty& _Left, const _Ty& _Right) const
        {    // apply operator!= to operands
        return (_Left != _Right);
        }
    };

 

二、bind1st 和 bind2nd

bind1st(const Fn2& Func,const Ty& left)  :1st指:传进来的参数应该放左边,也就是第一位
bind2nd(const Fn2& Func,const Ty& right) :2nd指:传进来的参数应该放右边,也就是第二位

简单的两个例子:

#include "stdafx.h"
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
#include <iterator>
#include<windows.h>
#include <Mmsystem.h>

using namespace std;

void ShowArray(vector<int> &Vec)
{
    vector<int>::iterator it = Vec.begin();
    //it 是一个地址  
    while (it < Vec.end())
    {
        cout << *it << endl;
        it++;
    }

};
int _tmain(int argc, _TCHAR* argv[])
{
    int a[] = { 1, 2, 100, 200 };
    std::vector<int> arr(a, a + 4);

    // 移除全部小于100的元素
    arr.erase(std::remove_if(arr.begin(), arr.end(),
        std::bind2nd(std::less< int>(), 100)), arr.end());
    ShowArray(arr);
    /**************************************/
    printf("*******************************\n");
    int b[] = { 1, 2, 100, 200 };
    std::vector<int> arr2(b, b + 4);
    // 移除全部大于100的元素
    arr2.erase(std::remove_if(arr2.begin(), arr2.end(),
        std::bind1st(std::less< int>(), 99)), arr2.end());
    ShowArray(arr2);
}

本例中由于仅判断是否为0 ,全部采用bind1st 和 bind2nd都同样。

 

三、remove_copy_if

remove_copy_if() 函数原型

template<class _InIt,class _OutIt,class _Pr> 
  inline _OutIt remove_copy_if(_InIt _First, _InIt _Last,
        _OutIt _Dest, _Pr _Pred)
    {    
// copy omitting each element satisfying _Pred
    _DEBUG_RANGE(_First, _Last);
    _DEBUG_POINTER(_Dest);
    _DEBUG_POINTER(_Pred);
    return (_Remove_copy_if(_Unchecked(_First), _Unchecked(_Last),
        _Dest, _Pred,
        _Is_checked(_Dest)));
    }

 

remove_copy_if()的思考方式和copy_if()相反,若IsNotZero為true,則不copy,若為false,則copy。

 

remove_copy_if(Vec1.begin(), Vec1.end(), back_inserter(Vec2), IsNotZero);

此时要求: 当unexpectedInt 为0时,返回值为TRUE,不进行拷贝;当unexpectedInt 不为0时,返回值为FALSE,则进行copy。

bool IsNotZero(int unexpectedInt)
{
    return (unexpectedInt == 0);
}

 

 

2、三种不一样方法来实现将查找拷贝操做

完成代码以下: 开发环境 VS2013 IDE

// Vector.cpp : 定义控制台应用程序的入口点。
//


/*
问题:
给定一个 vector:v1 = [0, 0, 30, 20, 0, 0, 0, 0, 10, 0],
但愿经过 not_equal_to 算法找到到不为零的元素,并复制到另外一个 vector: v2
*/

/*
要点一:
    第一步、利用not_equal_to函数进行数值比较,区分vector某一元素是不是非0数据
    第二步、查找全部的非0元素
    第三步、将全部非0元素拷贝到v2中来
要点二:效率问题
    测试结果:
    利用下标耗费时间最少,运行速度比较快,但不通用(vector能够利用下标)。
    利用迭代器耗费时间较多,但更为通用。
    利用C++ 11 remove_copy_if() algorithm 进行分析

总结:
    C++ 11 remove_copy_if() algorithm 代码最少,效率最高。

*/


#include "stdafx.h"
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
#include <iterator>
#include<windows.h>
#include <Mmsystem.h>
using namespace std;
#pragma comment( lib,"winmm.lib" )


//利用下标的方法

void FiltArray0(vector<int> &Vec1, vector<int> &Vec2, const int unexpectedInt)
{
    //测试时间
    LARGE_INTEGER litmp;
    LONGLONG qt1, qt2;
    double dft, dff, dfm;
    QueryPerformanceFrequency(&litmp);//得到时钟频率
    dff = (double)litmp.QuadPart;
    QueryPerformanceCounter(&litmp);//得到初始值
    //测试时间开始
    qt1 = litmp.QuadPart;

    int size = Vec1.size();
    for (int i = 0; i<size; i++)
    {
        if (not_equal_to<int>()(Vec1[i], unexpectedInt))
        {
            Vec2.push_back(Vec1[i]);
        }
        else
            continue;
    }

    QueryPerformanceCounter(&litmp);//得到终止值
    qt2 = litmp.QuadPart;
    dfm = (double)(qt2 - qt1);
    dft = dfm / dff;//得到对应的时间值
    cout<<"下标方法测试时间为:" << dft << endl;

}




//使用迭代器
void FiltArray1(vector<int> &Vec1, vector<int> &Vec2, const int unexpectedInt)
{
    //测试时间
    LARGE_INTEGER litmp;
    LONGLONG qt1, qt2;
    double dft, dff, dfm;
    QueryPerformanceFrequency(&litmp);//得到时钟频率
    dff = (double)litmp.QuadPart;
    QueryPerformanceCounter(&litmp);//得到初始值
    //测试时间开始
    qt1 = litmp.QuadPart;

    //查找第一个不为0的数值
    vector<int>::iterator result = find_if(Vec1.begin(), Vec1.end(), bind2nd(not_equal_to<int>(), unexpectedInt));
    while (result != Vec1.end())
    {
        Vec2.push_back(*result);
        //result结果的下一位开始查找不为0的数
        result = find_if(result + 1, Vec1.end(), bind2nd(not_equal_to<int>(), unexpectedInt));
    }

    QueryPerformanceCounter(&litmp);//得到终止值
    qt2 = litmp.QuadPart;
    dfm = (double)(qt2 - qt1);
    dft = dfm / dff;//得到对应的时间值
    cout << "迭代器方法测试时间为:" << dft << endl;


}


bool IsNotZero(int unexpectedInt)
{
    return (unexpectedInt == 0);
}

void FiltArray2(vector<int> &Vec1, vector<int> &Vec2, const int unexpectedInt)
{

    //测试时间
    LARGE_INTEGER litmp;
    LONGLONG qt1, qt2;
    double dft, dff, dfm;
    QueryPerformanceFrequency(&litmp);//得到时钟频率
    dff = (double)litmp.QuadPart;
    QueryPerformanceCounter(&litmp);//得到初始值
    //测试时间开始
    qt1 = litmp.QuadPart;

    // C++ 11 里的函数
    //《effective STL》 :尽可能用算法替代手写循环;查找少不了循环遍历
    remove_copy_if(Vec1.begin(), Vec1.end(), back_inserter(Vec2), IsNotZero);

    QueryPerformanceCounter(&litmp);//得到终止值
    qt2 = litmp.QuadPart;
    dfm = (double)(qt2 - qt1);
    dft = dfm / dff;//得到对应的时间值
    cout << "利用拷贝算法测试时间为:" << dft << endl;

}





void ShowArray(vector<int> &Vec)
{
    vector<int>::iterator it = Vec.begin();
    //it 是一个地址  
    while (it < Vec.end())
    {
        cout << *it << endl;
        it++;
    }


}

void ClearArray(vector<int> &Vec)
{
    vector<int>::iterator it = Vec.begin();
    //清空数据
    while (it < Vec.end())
    {
        it = Vec.erase(it);
    }

}

int main()
{  
    vector<int> v1{ 0, 0, 30, 20, 0, 0, 0, 0, 10, 0 };
    vector<int> v2;
    const int unexpectedInt = 0;
    /*
    方案一:   利用数组下标sanzho
    */
    FiltArray0(v1, v2, unexpectedInt);
    cout << "利用数组下标方案,V2中数据为:" << endl;
    ShowArray(v2);
    /*
    方案二:   利用迭代器
    */
    ClearArray(v2);
    FiltArray1(v1, v2, unexpectedInt);
    cout << "利用迭代器方案,V2中数据为:" << endl;
    ShowArray(v2);
    /*
    方案三:    利用拷贝算法
    */
    ClearArray(v2);
    FiltArray2(v1, v2, unexpectedInt);
    cout << "利用拷贝算法,V2中数据为:" << endl;
    ShowArray(v2);
    return 0;
}

 

 

3、效率对比

运行了几回,来观察实际运行时间。

 

 

等等。综合发现DEBUG模式下。

  第三种方案的运行时间最长,代码量最少。

  第二种方案的运行时间最长,更为通用。

  第一种方案的运行时间居中,但不通用。

 

Release模式下,数据以下图所示:

 

 

 

 

 

 

数据整理,对好比下表所示:

  下标操做 迭代器操做 remove_copy_if()算法操做
Debug统计数据一 0.000015762 0.0000395882 0.00000733115
Debug统计数据二 0.00000879738 0.000023093 0.00000806426
Debug统计数据三 0.00000879738 0.0000373889 0.00000733115
Release模式一 0.00000146623 0 0
Release模式二 0.00000146623 0.000000366557 0.000000366557
Release模式三 0.00000146623 0.00000109967 0.000000366557

 

对比发现,Release版本通过优化后,模式使用迭代器耗费的时间下降了很多。此时居然比下标运行时间还要短!

 

4、进一步的思考与总结

1)效率相比本身手写更高;STL的代码都是C++专家写出来的,专家写出来的代码在效率上很难超越; 
2)千万注意要使用++iter 不能使用iter++,iter++ 是先拷贝一份值,再进行++,效率很低;

3)经过分析,用algorithm+functional进行遍历效率最高。并且 下标索引的方式老是会效率高于迭代器方式。

那么为何迭代器速率比较慢呢?
其中的一位网友的解释:std::vector::end()的原型
    iterator end() _NOEXCEPT
        {    // return iterator for end of mutable sequence
        return (iterator(this->_Mylast, this));
        }

    const_iterator end() const _NOEXCEPT
        {    // return iterator for end of nonmutable sequence
        return (const_iterator(this->_Mylast, this));
        }

 

在Debug模式下,每次判断itr != Vec.end()的时候,都要进行从新构造一个迭代器并进行返回,这样固然下降的效率。
 
但同时,迭代器具备良好的通用性,在效率要求不是那么高的状况下,其实用哪一个都无所谓!
 
 
4)push_back耗费时间复杂度分析,有一篇文章解释的清晰明了,估计看了就没明白为何时间会差距这么大。
   (转帖) http://blog.sina.com.cn/s/blog_a2a6dd380102w73e.html
内容以下:

      vectorSTL中的一种序列式容器,采用的数据结构为线性连续空间,它以两个迭代器 start 和 finish 分别指向配置得来的连续空间中目前已被使用的范围,并以迭代器end_of_storage 指向整块连续空间(含备用空间)的尾端,结构以下所示:

    template Alloc = alloc>

    class vector {

  ​  ...

    protected:

        iterator start;                     // 表示目前使用空间的头

        iterator finish;                   // 表示目前使用空间的尾

        iterator end_of_storage;  // 表示可用空间的尾​

     ...};​

     咱们在使用 vector 时​,最常使用的操做恐怕就是插入操做了(push_back),那么当执行该操做时,该函数都作了哪些工做呢?

    该函数首先检查是否还有备用空间,若是有就直接在备用空间上构造元素,并调整迭代器 finish,使 vector 变大。若是没有备用空间了,就扩充空间,从新配置、移动数据,释放原空间。​

    其中​判断是否有备用空间,就是判断  finish 是否与 end_of_storage 相等.若是 

finish != end_of_storage,说明还有备用空间,不然已无备用空间。

    当执行 push_back 操做,该 vector 须要分配更多空间时,它的容量(capacity)会增大到原来的 倍。​如今咱们来均摊分析方法来计算 push_back 操做的时间复杂度。

    假定有 n 个元素,倍增因子为 m。那么完成这 n 个元素往一个 vector 中的push_back​操做,须要从新分配内存的次数大约为 logm(n),第 i 次从新分配将会致使复制 m^i (也就是当前的vector.size() 大小)个旧空间中元素,所以 n 次 push_back 操做所花费的总时间约为 n*m/(m - 1):

 

时间复杂度计算
 

    很明显这是一个等比数列.那么 n 个元素,n 次操做,每一次操做须要花费时间为 m / (m - 1),这是一个常量.

    因此,咱们采用均摊分析的方法可知,vector 中 push_back 操做的时间复杂度为常量时间.​

 
 
 
 
 
 
 
 
 
 
 
           
                                             2016.08.22



 

 

 

 

 

 

 

 

                                  

 

相关文章
相关标签/搜索