将值与矢量值进行比较

compare a value with a vector value

本文关键字:比较      更新时间:2023-10-16

我可以将整数值与向量值进行比较吗?

我正在尝试搜索用户是否输入否,匹配矢量 id 否

int no;
cout << "Input a no";
cin >> no;    
for (int n=0;vector.size();n++){
if(no==vector[n].getID()){
...
}
}

在 C++11 中,您可以将find_iflambda 函数一起使用来检测匹配的 ID,如下所示:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct user {
    int userid;
    string name;
    user(int id, string n) : userid(id), name(n) {}
};
int main() {
    vector<user> v;
    v.push_back(user(1, "quick"));
    v.push_back(user(2, "brown"));
    v.push_back(user(3, "fox"));
    v.push_back(user(4, "jumps"));
    auto needId = 3;
    // Here is the part that replaces the loop in your example:
    auto res = find_if(v.begin(), v.end(), [needId](user const& u) {
        return u.userid == needId;
    });
    // res is an interator pointing to the item that you search.
    if (res != v.end()) {
        cout << res->name << endl;
    }
    return 0;
}

这将打印fox ,如预期的那样(链接到 ideone)。

首先,我假设没有。 你是说数字。所以 cin 发生的事情是你得到一个字符串。然后需要将其转换为 int 与向量进行比较,这就是我认为您正在使用的。然后,只需将 noAsNumber 与向量 [i] 值进行比较。

string no;
int noAsNumber = atoi(no.c_str());
int i;
for (i = 0; i < vector.size(); i++)
{
    ...
}