[英]C++ : Array of struct as function parameter
我有一个结构:
typedef struct
{
int nNum;
string str;
}KeyPair;
假设我初始化了我的结构:
KeyPair keys[] =
{ {0, "tester"},
{2, "yadah"},
{0, "tester"}
};
我想在函数中使用初始化的值。 如何将此数组结构作为函数参数传递?
我有:
FetchKeys( KeyPair *pKeys)
{
//get the contents of keys[] here...
}
怎么样?
template<int N> void FetchKeys(KeyPair const (&r)[N]){}
编辑2:
甚至
template<int N> void FetchKeys(KeyPair const (*p)[N])
与作为
FetchKeys(&keys);
您可以按照@MSalters所述进行操作,也可以创建std::vector<KeyPair>
并将其传递给函数。 这是一个示例代码:
using namespace std;
struct KeyPair
{
int nNum;
string str;
};
void fetchKeys(const vector<KeyPair>& keys)
{
//Go through elements of the vector
vector<KeyPair>::const_iterator iter = keys.begin();
for(; iter != keys.end(); ++iter)
{
const KeyPair& pair = *iter;
}
}
int main()
{
KeyPair keys[] = {{0, "tester"},
{2, "yadah"},
{0, "tester"}
};
//Create a vector out of the array you are having
vector<KeyPair> v(keys, keys + sizeof(keys)/sizeof(keys[0]));
//Pass this vector to the function. This is safe as vector knows
//how many element it contains
fetchKeys(v);
return 0;
}
应该
// Definition
void FetchKeys( KeyPair *pKeys, int nKeys)
{
//get the contents of keys[] here...
}
// Call
FetchKeys(keys, sizeof(keys)/sizeof(keys[0]));
您只需调用FetchKeys(keys);
编辑
注意声明FetchKeys
的返回类型。
编辑2
如果还需要项数,则将大小添加为FetchKeys
输入参数:
void FetchKeys(KeyPair*, size_t size);
并调用FetchKeys(keys, sizeof(keys)/sizeof(*keys));
顺便说一句,如果可以的话,请编辑您的第一篇文章来陈述您的所有问题。
在c / c ++中,数组的名称(任何类型)都代表数组第一个元素的地址,因此key和&keys [0]是相同的。 您可以将其中任何一个传递给KeyPair *。
根据您要执行的操作,您甚至可以使用增强范围并将其传递为一对迭代器:
void FetchKeys(KeyPair *begin, KeyPair *end)
FetchKeys(boost::begin(keys), boost::end(keys));
看到这个答案: 如何通过引用C ++中的函数来传递数组?
将其包裹在一个结构中,美观又轻松。
#include <iostream>
struct foo
{
int a;
int b;
};
template <typename _T, size_t _size>
struct array_of
{
static size_t size() { return _size; }
_T data[_size];
};
template <typename _at>
void test(_at & array)
{
cout << "size: " << _at::size() << std::endl;
}
int main(void)
{
array_of<foo, 3> a = {{ {1,2}, {2,2}, {3,2} }};
test(a);
}
编辑:抱歉,我看不到工具栏来正确设置代码格式,希望标签能正常工作。
我使用VS 2008,这对我来说很好。
#include "stdafx.h"
typedef struct
{
int nNum;
CString str;
}KeyPair;
void FetchKeys( KeyPair *pKeys);
int _tmain(int argc, _TCHAR* argv[])
{
KeyPair keys[] =
{ {0, _T("tester")},
{2, _T("yadah")},
{0, _T("tester")}
};
FetchKeys(keys); //--> just pass the initialized variable.
return 0;
}
void FetchKeys(KeyPair *pKeys)
{
printf("%d, %s\n",pKeys[0].nNum, pKeys[0].str);
}
我不明白困难。 如果我错了纠正我。 为简单起见,我避免使用矢量,模板等。edit:要知道struct的大小,可以再传递一个arg。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.