[英]How to put initialized structs in a struct?
我有一個結構:
typedef struct
{
int nNum;
string str;
}KeyPair;
然后,我將結構初始化為如下形式:
KeyPair keys[] =
{
{0, "tester"},
{2, "yadah"},
{0, "tester"}
};
但是,讓我們說一些其他的初始化:
KeyPair keysA[] =
{
{0, "tester"},
{2, "yadah"},
{0, "tester"}
};
KeyPair keysB[] =
{
{0, "testeras"},
{2, "yadahsdf"},
{3, "testerasss"}
};
KeyPair OtherkeysA[] =
{
{1, "tester"},
{2, "yadah"},
{3, "tester"}
};
還有20多首
現在,如何創建另一個結構並對其進行初始化,使其包含這些已初始化的KeyPair?
這樣做的原因是因為我將反復調用其參數將用於這些結構的函數。 我不想這樣做:
pressKeyPairs( keys, sizeof( keys) / sizeof( keys[0] ) );
pressKeyPairs( keysA, sizeof( keysA) / sizeof( keysA[0] ) );
pressKeyPairs( keysB, sizeof( keysB) / sizeof( keysB[0] ) );
pressKeyPairs( OtherkeysA, sizeof( OtherkeysA) / sizeof( OtherkeysA[0] ) );
and so on...
所以我只想遍歷一個包含這些KeyPair的初始化實例的結構...
或者我想將這些KeyPairs的初始化實例放入向量中,然后循環遍歷向量...我該怎么做?
假設您有固定數量的密鑰對,則可以使用結構成員函數:
typedef struct KeyPairs {
KeyPair keysA[3];
KeyPair keysB[3];
KeyPair otherKeysA[3];
void init() {
keysA[0].nNum = 0;
keysA[0].str = "tester";
keysA[1].nNum = 2;
keysA[1].str = "yadah";
keysA[2].nNum = 0;
keysA[2].str = "tester";
// and so on for other keys
}
} KeyPairs;
然后像這樣使用它:
KeyPairs pairs;
pairs.init();
如何進行真正的C ++和使用構造函數?
(請注意,typedef是C ++中的隱式結構)
struct KeyPair
{
int nNum;
string str;
public:
KeyPair() {}
KeyPair(int n, string s) : nNum(n), str(s) {}
};
然后使用另一個結構:
struct TripleKeyPair
{
KeyPair keys[3];
TripleKeyPair()
{
// Your initialisation code goes here
}
};
最后,我不建議使用諸如以下名稱:
按鍵A,按鍵B,按鍵C ...
數組正是為此目的。 為什么要注意使用std :: vector ?
如何將“空”對象用作數組中的分隔符? 但是,您將不得不使用構造函數:
struct KeyPair
{
KeyPair() : fIsEmpty(true) {}
KeyPair(int nNum_, const char *szStr) : nNum(nNum_), str(szStr), fIsEmpty(false) {}
int nNum;
string str;
bool fIsEmpty;
};
然后您可以像這樣初始化它:
KeyPair allKeys[] =
{
KeyPair(0, "testeras"),
KeyPair(2, "yadahsdf"),
KeyPair(3, "testerasss"),
KeyPair(),
KeyPair(0, "tester"),
KeyPair(2, "yadah"),
KeyPair(3, "tester"),
KeyPair(1, "moreyadah"),
KeyPair()
};
如果為KeyPair對象數組實現一種strlen()模擬,那么迭代就很簡單了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.