c++11 高效将一个vector放置数据另外一个vector尾部的方式

C++将一个vector中的内容复制到另一个vector结尾。

可以参考:https://www.codingdict.com/questions/95161

   
template < typename T, typename RAIt >
void append(RAIt src_begin, RAIt src_end, std::vector<T>& dst,
            std::random_access_iterator_tag)
{
    auto src_size = src_end - src_begin;

    dst.resize( dst.size() + src_size );

    // copy is not required to invoke capacity checks
    std::copy( src_begin, src_end, dst.end() - src_size );
    // ^this^ should move with the example provided above
}

template < typename T, typename FwdIt >
void append(FwdIt src_begin, FwdIt src_end, std::vector<T>& dst)
{
    append( src_begin, src_end, dst,
            typename std::iterator_traits<FwdIt>::iterator_category() );
}

template < typename T, typename FwdIt >
void append_move(FwdIt src_begin, FwdIt src_end, std::vector<T>& dst)
{
    append( std::make_move_iterator(src_begin),
            std::make_move_iterator(src_end),
            dst );
}


int main() {
    // 构造6亿数据
    std::vector<int> tmp;
    tmp.reserve(600000000);
    for (int i = 0; i < 600000000; i++) {
        tmp.emplace_back(i);
    }

   {
        CostTime cst1("insert");
        std::vector<int> tmp3;
        tmp3.insert(tmp3.end(), tmp.begin(), tmp.end());
    }

   {
        CostTime cst1("insert + reserve");
        std::vector<int> tmp5;
        tmp5.reserve( tmp5.size() + (tmp.end() - tmp.begin()) );
        tmp5.insert(tmp5.end(), tmp.begin(), tmp.end());
    }

   {
        CostTime cst1("std::copy");
        std::vector<int> tmp4;
        append_move(tmp.begin(), tmp.end(), tmp4);
    }

 return 0;
}

测试结果:
insert real time = 0.680548s
insert + reserve real time = 0.697221s
std::copy real time = 1.95619s

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注