So, I'm attempting to add pairs to a vector, but they must successfully pass 2 criteria:
It specifically must be done while the function returns a void type, however for some reason, this logic doesn't seem to be working. Any suggestions?
void add(KEY_T key, WEIGHT_T weight)
{
bool contains = false;
if (weight < 0)
{
std::cout << "ERROR, invalid weight" << std::endl; //Throw error.
}
for (int x = 0; x < _valueToWeightMap.size(); x++)
{
if (_valueToWeightMap[x].first == key)
{
contains = true;
}
}
if (weight > 0 && contains == false)
{
_valueToWeightMap.push_back(std::make_pair(key, weight));
}
}
Here is the main:
int main()
{
DiscreteDistribution<std::string> dist1;
dist1.add("Helmet", -1);
dist1.add("Gloves", 5);
dist1.add("Gloves", 5);
dist1.add("cloud", 8);
For some reason, I'm not getting an error when I try to add Helmet as -1. Any suggestions?
This line:
std::cout << "ERROR, invalid weight" << std::endl; //Throw error.
does not do what the comment says (throw an error). This line:
throw "ERROR, invalid weight"; //Throw error.
does. However, I strongly recommend that you only ever throw exceptions derived from std::exception
. This:
throw std::range_error("ERROR, invalid weight"); //Throw error.
is much better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.