Concatenating two std::vectors

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

How do I concatenate two std::vectors?

25条回答
  •  孤街浪徒
    2020-11-22 12:14

    If your goal is simply to iterate over the range of values for read-only purposes, an alternative is to wrap both vectors around a proxy (O(1)) instead of copying them (O(n)), so they are promptly seen as a single, contiguous one.

    std::vector A{ 1, 2, 3, 4, 5};
    std::vector B{ 10, 20, 30 };
    
    VecProxy AB(A, B);  // ----> O(1)!
    
    for (size_t i = 0; i < AB.size(); i++)
        std::cout << AB[i] << " ";  // ----> 1 2 3 4 5 10 20 30
    

    Refer to https://stackoverflow.com/a/55838758/2379625 for more details, including the 'VecProxy' implementation as well as pros & cons.

提交回复
热议问题