简体   繁体   English

如何为向量编写 if 和 else 语句?

[英]How to write a if and else statement for a vector?

I would like to know how i can write an if and else statement for a vector.我想知道如何为向量编写 if 和 else 语句。 So let's say i have a vector which includes 1,2,3,4,5.所以假设我有一个包含 1,2,3,4,5 的向量。 I want the if statement to return a string if the number 1 is inside the vector.如果数字 1 在向量内,我希望 if 语句返回一个字符串。 I know how to structure it but how do i write the statement.我知道如何构造它,但我如何编写语句。 I have writen an example below with question marks because I'm unsure what is supposed to be in the brackets.我在下面写了一个带问号的例子,因为我不确定括号里应该是什么。

vector <int> myvec {1,2,3,4,5};
if (myvec??? 1) [
cout << "yes it is there" << endl;

]

You might use std::find :您可以使用std::find

std::vector<int> myvec {1,2,3,4,5};
if (std::find(myvec.begin(), myvec.end(), 1) != myvec.end()) {
    cout << "yes it is there" << endl;
}

Various options.各种选择。 One is一个是

 if (std::count(myvec.begin(), myvec.end(), 1) > 0)
 {
      cout << "yes it is there" << endl;
 }

This will detect the presence of one or more elements with value 1 .这将检测一个或多个值为1元素的存在。 If you want to test if there is exactly one element with value 1 , change the > 0 to == 1 .如果您想测试是否只有一个元素值为1 ,请将> 0更改为== 1

You can use:您可以使用:

if (std::find(myvec.begin(), myvec.end(), 1) != myvec.end()) {
   ...
}

I think it will be better to use a function that expresses what you want to do.我认为最好使用一个表达你想要做什么的函数。

if ( vector_contains_item(myvec, 1) ) {
   ...
}

You push the details of the logic to the function.您将逻辑的详细信息推送到函数。

bool vector_contains_item(std::vector<int> const& myvec, int item)
{
    return (std::find(myvec.begin(), myvec.end(), item) != myvec.end());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM