我想从整数列表中找到最大的数字。
例如,如果输入= (-10, -47, 3, 4,100,12,200,1)
,则最大数量为200,我想要找到的数字为100。
这是我的程序,
template<typename T>
T MaxElem(T t, T s)
{
return std::max(t, s);
}
template<typename T, typename ...A>
T MaxElem(T a, T b, A...x)
{
return MaxElem(MaxElem(a,b), x...);
}
template<typename T>
T Second(T t1, T t2)
{
return (t1 < t2)? t2 : t1;
}
template<typename T>
T Second(T t1, T t2, T x)
{
return (t1 < t2) ? ((t2 == x)? t1 : t2) : t1;
}
template<typename T, typename ...args>
T Second(T t1, T t2, args...a)
{
return Second(Second(t1, t2, MaxElem(t1, t2, a...)), a...);
}
输出200作为错误结果。
答案 0 :(得分:3)
我认为下面有一个简单的方法:
std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());
cout << numbers[1] ; // second largest
答案 1 :(得分:3)
你的第二个需要调整:
string sql = @"INSERT INTO CC_MSD_LIMS_STAGING (SMN, FACILITY_ID,SCHEDULE_DATE, IND_NAME, ADDRESS_LINE_1, ADDRESS_LINE_2, CITY, STATE, ZIP, SMPL_PT_DESC, SMPL_PT_NUM, SPLIT, TRUCK_ID, PROJECT_TYPE, SAMPLER, IND_ID, BOTTLE_TYPE, PRESERVATIVE, SAMPLE_TYPE, POLLUTANT, UNITS, SIU_IND, SURCHARGE_IND, SPECIAL_INSTRUCTIONS, AUTOSAMPLER_READY, SHIFT_L, SHIFT_START_TIME, PRIMARY_CONTACT_FIRSTNAME, PRIMARY_CONTACT_LASTNAME, PRIMARY_CONTACT_PHONE, ALTERNATE_CONTACT_FIRSTNAME, ALTERNATE_CONTACT_LASTNAME, ALTERNATE_CONTACT_PHONE, MONITORING_ID)
VALUES ('1793175', '1037247400', '11/13/2017 12:00:00 AM', 'STONETRENDS LLC', '18092 Chesterfield Airport', '', 'Chesterfield', 'MO', '63005', '6"" PVC vent 140'' S, 4'' W of NW crnr of bldg', '001', 'N', '493', 'IM', 'M', '2464', 'P0', 'None', 'T04', 'T208000', 'mg/L', '', 'Y', '', 'Y', '1', '0700AM', 'Patrick ', 'Martin', '6365371607', 'Stefan ', 'Landgraf', '6365371607', '-1')";
返回#include <algorithm>
template<typename T>
T MaxElem(T t, T s)
{
return std::max(t, s);
}
template<typename T, typename ...A>
T MaxElem(T a, T b, A...x)
{
return MaxElem(MaxElem(a, b), x...);
}
template<typename T>
T Second(T t1, T t2)
{
return (t1 < t2) ? t1 : t2; //here
}
template<typename T>
T Second(T t1, T t2, T x)
{
return Second(t1, x) < Second(t2, x) ? (t2 == x ? t1 : t2) : (t1 == x ? t2 : t1); //and here
}
template<typename T, typename ...args>
T Second(T t1, T t2, args...a)
{
return Second(Second(t1, t2, MaxElem(t1, t2, a...)), a...);
}
int main()
{
std::cout << Second(-10, -47, 3, 4, 100, 12, 200);
return 0;
}
答案 2 :(得分:2)
您可以使用std::nth_element功能:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
std::vector<int> numbers{ -10, -47, 3, 4, 100, 12, 200, 1 };
std::nth_element(numbers.begin(), numbers.begin() + 1, numbers.end(), std::greater<int>());
std::cout << "The second largest element is " << numbers[1] << '\n';
}