矢量的结构 [英] Vector of Structures
问题描述
我有另一个人给我一些代码,我们有一个结构
I have some code given to me by another person in which we have a structure
struct Pair {
string s1;
string s2;
bool equivalent;
};
然后他建立这些结构的向量硬编码
Then he sets up a vector of these structs hard coded
std::vector<Pair> PairID;
staticdata() {
PairID={{"string","string2",true},
{"string","string3",true},
{"string","string4",false},
{"string","string7",false},
{"string3","string8",false}
};
}
< string2,true},
Unfortunately my compiler is complaining on the line PairID={{"string","string2",true},
为什么?他建议使用-std = c ++ 0x编译,但我的编译器(gcc 4.2)不支持这个。有一个简单的方法来转换代码,使其工作?为什么会失败?
Why is this? He suggested to compile using -std=c++0x but my compiler (gcc 4.2) does not support this. Is there an easy way to convert the code so it works? Why is it failing??
我使用的是Mac OSX,不想更新我的编译器
I am using Mac OSX and would prefer not to update my compiler
推荐答案
您的代码不是合法的C ++。 是合法的C ++ 0x,但语言有很多变化。所以如果你想把这个代码编译成C ++代码,你需要改变它。
Your code is not legal C++. It is legal C++0x but there have been many changes to the language. So if you want to compile this code as C++ code, you'll need to change it.
PigBen的解决方案是一种方法,它的问题是临时数据建造及
PigBen's solution is one way, the problem with it being the temporary data could be constructed & destroyed many times, or live for a long time.
这是另一种方式:
struct Pair {
string s1;
string s2;
bool equivalent;
};
Pair make_Pair(const string& s1, const string& s2, bool equivalent)
{
Pair ret;
ret.s1 = s1;
ret.s2 = s2;
ret.equivalent = equivalent;
return ret;
}
// somewhere in the init code...
std::vector<Pair> PairID;
PairID.push_back(make_Pair("string","string2",true));
PairID.push_back(make_Pair("string","string3",true));
PairID.push_back(make_Pair("string","string4",false));
PairID.push_back(make_Pair("string","string7",false));
PairID.push_back(make_Pair("string3","string8",false));
这篇关于矢量的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!