我有以下代码来计算“倍数”向量的最大绝对值(表示倍数的结构) - 在我的例子中,我有std::pair
和我自己的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
字段的代码块仅“可用”并在传递的结构为Triple
时执行?
答案 0 :(得分:1)
您可以为不同的部分编写2个重载:
last = None
for word in arr:
if word == "foo":
print word
if last == 'foo' and word == 'bar':
print 'foobar'
last = word
然后主要功能是
void absMaxOfVectorOfMultiples_third(std::pair<int, int>& data,
int& maximum,
int* elementOfMax,
int coordChoice)
{
// empty.
}
void absMaxOfVectorOfMultiples_third(Triple& data,
int& maximum,
int* elementOfMax,
int coordChoice)
{
if (coordChoice != 1 && coordChoice != 2) {
// if the third 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.third) > maximum) {
maximum = data.third;
*elementOfMax = 3;
}
}
}