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}
};
}
Unfortunately my compiler is complaining on the line PairID={{"string","string2",true},
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??
I am using Mac OSX and would prefer not to update my compiler
A vector, in computing, is generally a one-dimensional array, typically storing numbers. Vectors typically have fixed sizes, unlike lists and queues. The vector data structure can be used to represent the mathematical vector used in linear algebra.
You can actually create a vector of structs!
Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.
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'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.
Here's another way:
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));
Why is it failing?
Because it’s not valid C++. It will be, in C++0x. But as of yet, it’s just not valid. And since your compiler doesn’t yet support C++0x, you will need to do it the hard way, i.e. populate the vector one element at a time, or copy from a C array …:
Pair data[] ={ {"string","string2",true},
{"string","string3",true},
{"string","string4",false},
{"string","string7",false},
{"string3","string8",false} };
PairID.assign(data, data + sizeof(data) / sizeof(Pair));
(This will require the algorithm
and iterator
standard headers.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With