c++ - 如何在三元运算符中打破 for 循环

标签 c++ ternary

所以,一个方法是 cout<<"";如果条件为假,但我觉得这不是正确的方法并且 break似乎不起作用。有什么我应该知道的吗?

template <class T>
T get(const string &prompt) {
    cout<<prompt;
    T ret;
    cin>>ret;
    return ret;
}
   int main()
{
    vector<int>x;
        for(int i=0;i<1000;i++) x.push_back((rand()%1200+1200));
    int rating=get<int>("Your rating: ");x.push_back(rating);
        sortVector(x);
    for(int i=0;i<x.size();i++) ((x[i]==rating) ? cout<<"Found your rating on pozition "<<i : cout<<"");
}

最佳答案

三元运算符的每一部分都必须能够计算出相同的类型*,所以你不能有一部分输出(这将返回 cout 对象)而另一部分 打破的。

相反,在您的情况下,为什么不将条件添加到您的 for 中?

for(int i = 0; i < x.size() && x[i] == rating; i++) {
    cout<<"Found your rating on pozition ";
}

但这可能不是你真正想要的

您似乎在尝试查找某个项目在数组中的位置。如果是这种情况,而您只是在寻找第一次出现的情况,我建议您这样做:

int pos;
for(pos = 0; pos < x.size() && x[pos] != rating; pos++) { }

if(pos != x.size()) {
    cout<<"Found your rating on pozition " << pos;
} else {
    cout << "Couldn't find it!";
}

或者更好的是,使用 std::find !


*您也可以参与其中。感谢@Lightness!

关于c++ - 如何在三元运算符中打破 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328977/

相关文章:

java - NullPointerException 通过 Java 三元运算符的自动装箱行为

javascript - AJAX 初始化中的三元运算符未正确设置

无赋值的 Java 三元

c++ - 如何在用户创建的库中打开 Windows 资源管理器?

c++ - 将 opencv 的 cvScalar 与 Ycbcr 值一起使用

c++ - MFC 应用程序终止时运行自定义代码 : d'tor or WM_CLOSE?

c++ - 如果在头文件中定义函数,inline 关键字是否有意义?

c++ - MFC默认选择路径

javascript - 尝试弄清楚如何将具有多个条件的长三元运算符转换为长 if 语句

javascript - 嵌套三元 JavaScript