简体   繁体   English

使用另一个 const std::vector 和附加值创建一个 const std::vector

[英]Create a const std::vector with another const std::vector and additional values

Consider a const vector v1考虑一个常量向量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:我想用 vector v1的内容创建一个新的 const vector v2和附加值,如下所示:

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() :考虑以下便捷函数模板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 .它创建一个临时向量u ,其中包含传递给函数的向量的元素和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).请注意,便利函数按值返回const对象通常意义不大(例如,无法移动返回的对象)。 Therefore, the convenience function above returns a non- const vector instead, ie, std::vector<T> .因此,上面的便利函数返回一个非const向量,即std::vector<T> You can, however, initialize a const vector with this returned non- const vector, and it will be move initialized.但是,您可以使用返回的非const向量初始化const向量,它将被移动初始化。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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