简体   繁体   中英

Create a const std::vector with another const std::vector and additional values

Consider a const vector v1

const std::vector<int> v1{0, 1, 2, 3, 4};

I want to create a new const vector v2 with the contents of vector v1 with additional values like so:

const std::vector<int> v1{0, 1, 2, 3, 4};
const std::vector<int> v2{v1, 5, 6, 7, 8, 9};

How could I do this?

Consider the following convenience function template, make_vector() :

template<typename T>
std::vector<T> make_vector(const std::vector<T>& v, std::initializer_list<T> l) {
   std::vector<T> u(v);
   u.insert(u.end(), l.begin(), l.end());
   return u;
}

It creates a temporary vector u , which contains the elements of the vector passed to the function and the elements of the initializer_list .

Note that it usually makes little sense for the convenience function to return a const object by value (for example, the returned object can't be moved). Therefore, the convenience function above returns a non- const vector instead, ie, std::vector<T> . You can, however, initialize a const vector with this returned non- const vector, and it will be move initialized.

auto main() -> int {
   const std::vector<int> u{1, 2, 3};
   auto const v = make_vector(u, {4, 5, 6});

   for (auto elem: v)
      std::cout << elem << ' ';
   std::cout << '\n';
}

The output:

1 2 3 4 5 6 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM