「倍数」(倍数を表す構造体) のベクトルの最大絶対値を計算する次のコードがありstd::pair
ますTriple
。
/**
* @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
「利用可能」であり、渡された構造体がTriple
.