简体   繁体   English

将std :: array转换为std :: vector

[英]Converting std::array to std::vector

In the code below, the size of the function (foo) argument ( std::vector ) can be anything to make the function a generic one. 在下面的代码中,函数(foo)参数( std::vector )的大小可以是使函数成为通用函数的任何东西。 However, sometimes the size container is known so std::array can be used. 但是,有时大小容器是已知的,因此可以使用std :: array。 The problem is to convert the std::array to std::vector . 问题是将std::array转换为std::vector What is the best way to solve this problem? 解决这个问题的最佳方法是什么? Is it better to just use std::vector always in this case? 在这种情况下,总是使用std::vector总是更好吗?

#include <iostream>
#include <array>
#include <vector>

using namespace std;

// generic function: size of the container can be anything
void foo (vector<int>& vec)
{
    // do something
}

int main()
{
   array<int,3> arr; // size is known. why use std::vector?
   foo (arr); // cannot convert std::array to std::vector

   return 0;
}

Given that you pass in an array , foo does not seem to resize the container it gets passed in (however, it does seem to modify the elements since vec is passed non-const). 鉴于你传入一个arrayfoo似乎没有调整它传入的容器的大小(但是,它似乎修改了元素,因为vec是非const传递的)。 It therefore does not need to know anything about the underlying container other than how to access elements. 因此,除了如何访问元素之外,它不需要知道任何有关底层容器的信息。

Then, you can pass a pair of iterators (and make the iterator type a template argument), as many STL algorithms do. 然后,您可以传递一对迭代器 (并使迭代器类型成为模板参数),就像许多STL算法一样。

The function accepts a vector by reference. 该函数通过引用接受向量。 So there is no any sense to pass an object of type std::array to the function. 因此将std :: array类型的对象传递给函数没有任何意义。 It could have a sense if the parameter of the function would be defined as const reference to a vector. 如果函数的参数被定义为向量的const引用,则可能有意义。

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

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