我有一个接受可变大小数组的函数,但它仍然有些困惑,我无法将它压缩成更易于使用的东西。我不是要求被喂食,但我正在寻找一些关于如何可能补救这个问题的建议。
这是我必须设置变量以传递给函数的方法,非常乏味和冗余:
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/