我有以下代码来计算“倍数”(表示倍数的结构)向量的最大绝对值 - 在我的例子中,我有std::pair
's 和我自己的Triple
结构,它与前者基本相同,但有 3 个字段。
/**
* @brief Computes the maximum absolute value of a vector of specified structs
*
* Iterates through all elements of a vector checking the T.first, T.second and T.third
* values to find the abs maximum element of the data structure.
*
* @param data Vector of pairs of integers
* @param elementOfMax Pointer to integer which will store the element (1,2 or 3) that the maximum
* value of the vector of T structs is contained within, pass the address of an int variable as this param.
* @param coordChoice [= 0] Optional argument to choose specific 'x' or 'y' co-ordinate
* of the T struct to compute maximum for - set coordChoice to 1 for 1st element, 2
* for 2nd element (etc.) any other value will result in all elements being considered.
* @return maximum value of data
*/
template<typename T> int absMaxOfVectorOfMultiples(std::vector< T >& data, int* elementOfMax, int coordChoice = 0) {
// set initial maximum to 0
int maximum = 0;
*elementOfMax = 0;
bool isPair = false;
if (typeid(T).name() == typeid(std::pair<int, int>).name()) {
isPair = true;
}
// loop over all elements in the data vector
for (unsigned int i = 0; i < data.size(); i++) {
if (coordChoice != 2 && coordChoice != 3) {
// if the first element of the multipe struct at this data point
// is greater than current maximum, set this element
// to the new maximum value
if (std::abs(data.at(i).first) > maximum) {
maximum = data.at(i).first;
*elementOfMax = 1;
}
}
if (coordChoice != 1 && coordChoice != 3) {
// if the second element of the multiple struct at this data point
// is greater than current maximum, set this element
// to the new maximum value
if (std::abs(data.at(i).second) > maximum) {
maximum = data.at(i).second;
*elementOfMax = 2;
}
}
if (!isPair) {
if (coordChoice != 1 && coordChoice != 2) {
// if the third element of the multtiple struct at this data point
// is greater than current maximum, set this element
// to the new maximum value
if (std::abs(data.at(i).third) > maximum) {
maximum = data.at(i).third;
*elementOfMax = 3;
}
}
}
}
return maximum;
}
尽管尚未对此进行测试,但我知道在将std::pair
结构传递给函数时这将不起作用,因为一对中没有third
字段。我将如何更改此代码,以使用于获取和检查third
字段的代码块仅“可用”并在传递的结构为 a 时执行Triple
?