简体   繁体   English

在 C++ 中将 std::array 作为参数传递

[英]Passing an std::array as an argument in C++

I want to pass an std::array as an argument to a function, and I cannot find the correct way.我想将std::array作为参数传递给函数,但找不到正确的方法。

I am not talking about normal C array (eg int arr[2]={1,3}; ).我不是在谈论普通的 C 数组(例如int arr[2]={1,3}; )。 I am talking about std::array class, available from C++ 11.我说的是std::array类,可从 C++ 11 获得。

Example code:示例代码:

#include <iostream>
#include <array>

using namespace std;

class test
{
   void function(array<int> myarr)
   {
      // .......some code..........
   }
};

How do I pass an std::array to a function, as std::array takes two template arguments: std::array<class T, std::size_t N> , but while passing it as an argument I do not want to specify the size?如何将std::array传递给函数,因为std::array需要两个模板参数: std::array<class T, std::size_t N> ,但是在将其作为参数传递时我不想指定尺寸?

Not knowing the second template argument to std::array<> means your test class should be templated as well.不知道std::array<>的第二个模板参数意味着你的test类也应该被模板化。

template <std::size_t N>
class test
{
    void function(const std::array<int, N> & myarr)
    {
        // ...
    }
};

By the way, it's better to pass myarr as const & .顺便说一句,最好将myarr作为const &传递。

You could use an approach like:您可以使用以下方法:

#include<array>
using namespace std;

template <size_t N>
class test
{
    void function(const array<int, N> & myarr)
    {
        /* My code */
    }
};

But keep in mind that std::array is not a dynamic array.但请记住, std::array不是动态数组。 You have to know the sizes at compile time.您必须在编译时知道大小。

If you get to know the sizes later at runtime of your program you should consider using std::vector instead:如果您稍后在程序运行时知道大小,您应该考虑使用std::vector代替:

#include<vector>

using namespace std;

class test
{
    void function(const vector<int> & myvec)
    {
        /* My code */
    }
};

In that variant you don't need to pass the size at all.在该变体中,您根本不需要传递大小。

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

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