简体   繁体   English

如何使用 If 和 else 语句在向量中搜索

[英]How to search in vector with If and else statement

I have an issue with searching in a vector.我在向量中搜索时遇到问题。 Let's say I have a vector, the idea is to use if and else statements to check each element and then print out a string message.假设我有一个向量,想法是使用 if 和 else 语句来检查每个元素,然后打印出一个字符串消息。 So for example if there is a 1 at 0 then it should print out a message.因此,例如,如果 0 处有一个 1,那么它应该打印出一条消息。 The example below shows what I am trying to explain.下面的示例显示了我要解释的内容。 If there is 1 at 0 then print out a message.如果 0 处有 1,则打印出一条消息。

vector<int> myvec {1,2,3,4,5};

if (statement) {
  cout << "The number 1 is at 0";
}

At the moment I have tried this:目前我已经尝试过这个:

vector<int> myvec {1,2,3,4,5};

if (find(myvec.begin(), myvec.end(), 3) != myvec.end()) {
  cout << "yes it is there" << endl;
}

This only checks to see if 3 is in the vector but I want to find out if 1 is at 0.这只会检查 3 是否在向量中,但我想知道 1 是否为 0。

You're trying too hard, simply你太努力了,只是

if (myvec[0] == 1)

For extra security you could add a check that the vector is not empty为了获得额外的安全性,您可以添加一个检查向量是否为空

if (!myvec.empty() && myvec[0] == 1)

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

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