簡體   English   中英

C ++:結構數組作為函數參數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM