C ++:struct作为函数参数的数组

时间:2010-11-26 10:40:57

标签: c++ function parameters struct

我有一个结构:

typedef struct
{  
   int nNum; 
   string str;   
}KeyPair;

假设我初始化我的结构:

KeyPair keys[] = 
{    {0, "tester"},  
     {2, "yadah"},  
     {0, "tester"} 
};  

我想在函数中使用初始值。 如何将此数组结构作为函数参数传递?

我有:

FetchKeys( KeyPair *pKeys)
{
     //get the contents of keys[] here...   
}

8 个答案:

答案 0 :(得分:5)

怎么样?

template<int N> void FetchKeys(KeyPair const (&r)[N]){}

编辑2:

甚至

template<int N> void FetchKeys(KeyPair const (*p)[N])

呼叫为

FetchKeys(&keys);

答案 1 :(得分:4)

你可以像@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;

}

答案 2 :(得分:3)

应该是

// Definition
void FetchKeys( KeyPair *pKeys, int nKeys)
{
     //get the contents of keys[] here...   
}
// Call
FetchKeys(keys, sizeof(keys)/sizeof(keys[0]));

答案 3 :(得分:1)

您只需致电FetchKeys(keys);

修改

注意声明FetchKeys'返回类型。

编辑2

如果您还需要项目数,则将大小添加为FetchKeys输入参数:

void FetchKeys(KeyPair*, size_t size);

并致电FetchKeys(keys, sizeof(keys)/sizeof(*keys));

顺便说一下,如果可以,请通过编辑你的第一篇文章来陈述你的所有问题。

答案 4 :(得分:1)

在c / c ++中,数组的名称(任何类型)代表数组的第一个元素的地址,所以 键和键[0]是相同的。 您可以将其中任何一个传递给KeyPair *。

答案 5 :(得分:1)

根据您的想法,您甚至可以使用增强范围并将其作为一对迭代器传递:

void FetchKeys(KeyPair *begin, KeyPair *end)
FetchKeys(boost::begin(keys), boost::end(keys));

答案 6 :(得分:0)

请参阅此答案:How can I pass an array by reference to a function in 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);

}

编辑:URGH,我看不到工具栏正确格式化代码,希望标签有效..

答案 7 :(得分:0)

我使用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);

}

我不明白这个难点。如我错了请纠正我。为了简单起见,我避免使用矢量,模板等。 编辑:要知道struct的大小,你可以传递一个arg。