Construction a vector from the concatenation of 2 vectors

后端 未结 6 485
梦谈多话
梦谈多话 2021-01-12 22:45

Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)

For example:



        
6条回答
  •  情深已故
    2021-01-12 23:30

    Let me preface this by saying this is a hack, and will not give an answer to how to do this using a vector. Instead we'll depend on sizeof(int) == sizeof(char32_t) and use a u32string to contain our data.

    This answer makes it exceedingly clear that only primitives can be used in a basic_string, and that any primitive larger than 32-bits would require writing a custom char_traits, but for an int we can just use u32string.

    The qualification for this can be validated by doing:

    static_assert(sizeof(int) == sizeof(char32_t));
    

    Once size equality has been established, and with the knowledge that things like non-const data, and emplace or emplace_back cannot be used, u32string can be used like a vector, with the notable inclusion of an addition opperator:

    const vector first = {13};
    const vector second = {42};
    const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());
    

    [Live Example]

提交回复
热议问题