某網友問:
“
一個類中,有一個成員變量static set<int> SET,怎麼用一個1000個元素給它初始化?
”
一個類中特殊的成員變量的初始化是非常需要技巧的事情,以前針對這個問題專門寫過一篇博文:
但這篇博文,並沒有包括上面那位網友提出的問題,爲此給出以下代碼:
#include <set>
#include <iostream>
using namespace std;
class Test
{
private:
static set<int> SET;
public:
static void print()
{
for(set<int>::iterator iter = SET.begin(); iter != SET.end(); ++iter)
{
cout << *iter << endl;
}
}
};
set<int> init()
{
set<int> tmp;
for(int i = 0; i < 1000; ++i)
{
tmp.insert(i);
}
return tmp;
}
set<int> Test::SET(init()); // 注意前面必須要有set<int>
int main(int argc, char** argv)
{
Test::print();
return 0;
}