[英]Converting std::array to std::vector
在下面的代碼中,函數(foo)參數( std::vector
)的大小可以是使函數成為通用函數的任何東西。 但是,有時大小容器是已知的,因此可以使用std :: array。 問題是將std::array
轉換為std::vector
。 解決這個問題的最佳方法是什么? 在這種情況下,總是使用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;
}
鑒於你傳入一個array
, foo
似乎沒有調整它傳入的容器的大小(但是,它似乎修改了元素,因為vec
是非const傳遞的)。 因此,除了如何訪問元素之外,它不需要知道任何有關底層容器的信息。
然后,您可以傳遞一對迭代器 (並使迭代器類型成為模板參數),就像許多STL算法一樣。
該函數通過引用接受向量。 因此將std :: array類型的對象傳遞給函數沒有任何意義。 如果函數的參數被定義為向量的const引用,則可能有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.