Concatenating two std::vectors

后端 未结 25 2297
予麋鹿
予麋鹿 2020-11-22 12:00

How do I concatenate two std::vectors?

25条回答
  •  情歌与酒
    2020-11-22 12:30

    You can do it with pre-implemented STL algorithms using a template for a polymorphic type use.

    #include 
    #include 
    #include 
    
    template
    
    void concat(std::vector& valuesa, std::vector& valuesb){
    
         for_each(valuesb.begin(), valuesb.end(), [&](int value){ valuesa.push_back(value);});
    }
    
    int main()
    {
        std::vector values_p={1,2,3,4,5};
        std::vector values_s={6,7};
    
       concat(values_p, values_s);
    
        for(auto& it : values_p){
    
            std::cout<

    You can clear the second vector if you don't want to use it further (clear() method).

提交回复
热议问题