[英]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.