我可以将int值与矢量值进行比较吗?
我正在尝试搜索用户输入否,匹配向量ID否
int no;
cout << "Input a no";
cin >> no;
for (int n=0;vector.size();n++){
if(no==vector[n].getID()){
...
}
}
答案 0 :(得分:2)
在C ++ 11中你可以使用find_if
和 lambda函数来检测匹配的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
(link to ideone)。
答案 1 :(得分:-1)
首先,我假设没有。你的意思是数字。那么cin会发生什么,你得到一个String。然后需要将其转换为int与向量进行比较,这是我认为您正在使用的。然后,只需将noAsNumber与vector [i]值进行比较。
string no;
int noAsNumber = atoi(no.c_str());
int i;
for (i = 0; i < vector.size(); i++)
{
...
}