#include<iostream>
#include<string>
#include<ctime>
using namespace std;
int main()
{
int box1 = 30;
int box2 = 99;
int box3 = 140;
int box4 = 200;
int box5 = 220;
int box6 = 260;
int box7 = 300;
int box8 = 310;
int box9 = 500;
int box10 = 100;
return(0);
}
我尝试过这样的事情:
string var;
int i = 1;
for(i=1;i<=10;i++) {
var = "box" + std::to_string(i);
cout << var << endl;
}
但它一直告诉我std :: to_string是对重载函数的模糊调用。不知道从哪里开始。
答案 0 :(得分:6)
由于您询问*(proof that it works,preprocessed (scroll down for output)):
#include <algorithm>
#include <iostream>
#include <boost/preprocessor.hpp>
#define VAR_N(z, n, nameBase) BOOST_PP_CAT(nameBase, BOOST_PP_INC(n))
int main() {
int box1 = 30;
int box2 = 99;
int box3 = 140;
int box4 = 200;
int box5 = 220;
int box6 = 260;
int box7 = 300;
int box8 = 310;
int box9 = 500;
int box10 = 100;
std::cout << std::max({BOOST_PP_ENUM(10, VAR_N, box)}); //500
}
*严重的是,没有十个变量,其名称仅因连续数字而不同。这就是阵列的用途。
答案 1 :(得分:2)
即使您没有禁止使用数组,我也可能更喜欢vector
数组。
#include<iostream>
#include <algorithm>
int main()
{
std::vector<int> boxes{30, 99, 140, 200, 220, 260, 300, 310, 500, 100};
std::cout << *std::max_element(boxes.begin(), boxes.end());
}
看起来很简单。
答案 2 :(得分:2)
因为我们正在如此愉快地解构这个问题:
<强> Live On Coliru 强>
#include <algorithm>
#include <iostream>
int main() {
std::cout << std::max({ 30, 99, 140, 200, 220, 260, 300, 310, 500, 100});
}
不使用数组,甚至不作为向量或类似
的实现的一部分答案 3 :(得分:0)
此解决方案可以在不使用任何数组或数据结构的情况下找到最大值。
int main()
{
std::cout << 500;
}
答案 4 :(得分:0)
如果您只想找到max,那么您可以这样做:
示例代码:
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
void Max() {
}
int max_val=0;;
template<typename T , typename ... type_pack>
int Max(T x, const type_pack... rest) {
max_val=(max_val>x)?max_val:x;
Max(rest...);
return max_val;
}
int main()
{
int box1 = 30;
int box2 = 99;
int box3 = 140;
int box4 = 200;
int box5 = 220;
int box6 = 260;
int box7 = 300;
int box8 = 310;
int box9 = 500;
int box10 = 100;
std::cout<<Max(box1,box2,box3,box4,box5,box6,box7,box8,box9,box10);
return(0);
}
您可以将所有变量作为参数传递给函数Max()
(参数数量不固定),它将为您返回Max ...
不使用数组或任何循环(它使用递归)。