You have the coise to use a std::map where in your case name
is not longer part of your class. But you also can use a set which contains the name
inside the class and use it to find it from your container.
The following code provides both alternatives:
class CryptoStatsWithoutName {
public:
std::string lastPriceStr;
int lastPrice = 0;
int score = 0;
int priceHistory[2] = { 0,0 }; // one column for time, other for price
};
class CryptoStats{
public:
std::string name;
std::string lastPriceStr;
int lastPrice = 0;
int score = 0;
int priceHistory[2] = { 0,0 }; // one column for time, other for price
// a set is always be sorted, as this, it needs for user defined types
// a comparison operator
bool operator<( const CryptoStats& outer) const
{
return name< outer.name;
}
};
// if we want to use std::set<>::find we have to provide additional comparison operators
// if the key we search for is not the stored user defined type
bool operator<( const CryptoStats& cs, const std::string& key) { return cs.name < key; }
bool operator<( const std::string& key, const CryptoStats& cs) { return key < cs.name; }
int main()
{
std::map<std::string, CryptoStatsWithoutName> cryptoStatsWithoutName=
{
{"BTCUSD", {"1", 1, 1,{1,1}}},
{"ETHUSD", {"2" ,2, 2, {2,2}}}
};
// attention: if the key is not found, a new feault initialized element will be inserted into the map!
std::cout << cryptoStatsWithoutName[ "BTCUSD" ].lastPrice << std::endl;
std::set< CryptoStats, std::less<> > cryptoStats =
{
{"BTCUSD", "1", 1, 1,{1,1}},
{"ETHUSD", "2" ,2, 2,{2,2}}
};
// attention: If key is not found you access `end()` which will crash your prog. Better you check that your returned iterator is valid!
std::cout << cryptoStats.find("ETHUSD")->lastPrice << std::endl;
}
Attention:
If you search for a non existing key, the code will fail. In case of a map it will insert a new default initialized element with the given search key, which is not intended I believe. In the case with std::find you better have to check if find
with return end()
before accessing the returned data. In the last case your program may throw an exception or terminate by accessing non existent data.