c++ - 如何将花括号列表/动态数组传递给函数 (c++)

标签 c++

我有一个接受可变大小数组的函数,但它仍然有些困惑,我无法将它压缩成更易于使用的东西。我不是要求被喂食,但我正在寻找一些关于如何可能补救这个问题的建议。

这是我必须设置变量以传递给函数的方法,非常乏味和冗余:

DWORD xAAR[4] = { base, 0x5EC5E4, 0x5A8, 0x3C };
x = pGet(xAr, 5);

这是我想将其压缩的方式(请记住,每次使用的元素数量都会有所不同):

x = pGet({ base, 0x5EC5E4, 0x5A8, 0x3C });

下面是函数本身,为简洁起见,它的内容被排除在外。

DWORD pGet(DWORD p[], int sizeA)
{
    DWORD address;
    for (int i = 1; i < sizeA; i++)
    {
    }
    return NULL;
}

最佳答案

您可以使用以下一组函数来更轻松地处理大量容器。

template <typename Iterator>
DWORD pGet(Iterator begin, Iterator end)
{
   DWORD ret = 0;
   for (Iterator iter = begin ; iter != end; ++iter )
   {
      // Do something with the item.
   }
   return ret;
}

template <typename Container>
DWORD pGet(Container const& c)
{
   return pGet(std::begin(c), std::end(c));
}

DWORD pGet(std::initializer_list<DWORD> const& c)
{
   return pGet(std::begin(c), std::end(c));
}

用法:

int main()
{
   DWORD base = 10;

   // Use pGet with an array.
   DWORD xAAR[4] = { base, 0x5EC5E4, 0x5A8, 0x3C };
   pGet(xAAR);
   pGet(xAAR, xAAR+2); // Work with a subset of the array.

   // Use pGet with an initializer_list.
   pGet({ base, 0x5EC5E4, 0x5A8, 0x3C});

   // Use pGet with a vector.
   std::vector<DWORD> v = { base, 0x5EC5E4, 0x5A8, 0x3C };
   pGet(v);
   pGet(v.begin(), v.begin()+2); // Work with a subset of the vector

   // Use pGet with a set.
   std::set<DWORD> s = { base, 0x5EC5E4, 0x5A8, 0x3C };
   pGet(s);
}

关于c++ - 如何将花括号列表/动态数组传递给函数 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30994472/

相关文章:

c++ - 如何在 C 和 C++ 代码之间共享变量?

C++ 静态局部函数与全局函数

c++ - 如何从 QT UI 菜单栏(顶部菜单)开始打开文件(图像)

c++ - 设置一个等于自身的变量实际上在 C++ 中执行吗?

c++ - 在 boost-variant 中调用匹配类型的析构函数

c++ - 静态全局数组中的仿函数

c# - 如何下载整个网页

c++ - visual studio lnk2019 和 1120 错误

c++ - 为什么 UInt64 变量不能包含大于 UInt32::Max 的值?

c++ - 继续获取 "error: use of undeclared identifier ' cout' 和错误 : reference to overloaded function could not be resolved