Concatenating two std::vectors

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

How do I concatenate two std::vectors?

25条回答
  •  孤独总比滥情好
    2020-11-22 12:32

    This solution might be a bit complicated, but boost-range has also some other nice things to offer.

    #include 
    #include 
    #include 
    
    int main(int, char**) {
        std::vector a = { 1,2,3 };
        std::vector b = { 4,5,6 };
        boost::copy(b, std::back_inserter(a));
        for (auto& iter : a) {
            std::cout << iter << " ";
        }
        return EXIT_SUCCESS;
    }
    

    Often ones intention is to combine vector a and b just iterate over it doing some operation. In this case, there is the ridiculous simple join function.

    #include 
    #include 
    #include 
    #include 
    
    int main(int, char**) {
        std::vector a = { 1,2,3 };
        std::vector b = { 4,5,6 };
        std::vector c = { 7,8,9 };
        // Just creates an iterator
        for (auto& iter : boost::join(a, boost::join(b, c))) {
            std::cout << iter << " ";
        }
        std::cout << "\n";
        // Can also be used to create a copy
        std::vector d;
        boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));
        for (auto& iter : d) {
            std::cout << iter << " ";
        }
        return EXIT_SUCCESS;
    }
    

    For large vectors this might be an advantage, as there is no copying. It can be also used for copying an generalizes easily to more than one container.

    For some reason there is nothing like boost::join(a,b,c), which could be reasonable.

提交回复
热议问题