我在类中有以下两种方法,第一种是在搜索数据结构中的项时返回一对数据和关联的优先级,第二种是返回搜索到的所有数据实例对的向量:
/**
* @brief Searches for an item in the PQ and returns the item with corresponding priority
*
* @param item Object to search for in the priority queue
* @return A std::pair containing the object and its corresponding priority
* @throw Throws invalid_argument exception if item does not exist within queue
*/
std::pair<T, unsigned int> search(T& item) {
size_t i = 0;
// loop over whole queue
while (i < dataWithPriorityVec.size()) {
// if first element of dataVec at i equals the parameterised item,
// return the pair of the object and corresponding priority at the node
if (dataWithPriorityVec.at(i).first == item) {
return std::make_pair<T&, unsigned int&>(dataWithPriorityVec.at(i).first, dataWithPriorityVec.at(i).second);
}
i++;
}
// if item could not be found within queue, throw an exception
throw std::invalid_argument("Item does not exist within priority queue.");
}
/**
* @brief Searches for an item in the PQ and returns a vector of all occurrences of the item
* with their corresponding priorities.
*
* @warning If the item does not exist within the queue then this method will return an empty vector.
* @param item Object to search for in the priority queue
* @return A std::vector of std::pair instances containing the objects and corresponding priorities
*/
std::vector<std::pair<T, unsigned int>> searchAll(T& item) {
size_t i = 0;
// container to store occurrences of data pairs in the queue
std::vector<std::pair<T, unsigned int>> occurrencesVec;
// loop over whole queue
while (i < dataWithPriorityVec.size()) {
// if first element of dataVec at i equals the parameterised item,
// push the pair containing the data and corresponding priority
// to the occurrencesVec container
if (dataWithPriorityVec.at(i).first == item) {
occurrencesVec.push_back(std::make_pair<T&, unsigned int&>(dataWithPriorityVec.at(i).first, dataWithPriorityVec.at(i).second));
}
i++;
}
return occurrencesVec;
}
请注意,在第一个方法(搜索)中,如果项目在结构中不存在,则抛出异常,而在第二个(searchAll)中,如果项目不存在,我只是让方法返回一个空向量。我对这种脱节感到不安,但我不想为了它而抛出异常 - 有没有一种标准的方法可以解决这个问题,还是归结为编码偏好?
我理解异常抛出通常只能在方法无法实现其设计目的并且结果不能忽略时才能完成 - 但是似乎在searchAll情况下返回空向量并不是一件错误的事情。