将值与矢量值进行比较
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_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
,如预期的那样(链接到 ideone)。
首先,我假设没有。 你是说数字。所以 cin 发生的事情是你得到一个字符串。然后需要将其转换为 int 与向量进行比较,这就是我认为您正在使用的。然后,只需将 noAsNumber 与向量 [i] 值进行比较。
string no;
int noAsNumber = atoi(no.c_str());
int i;
for (i = 0; i < vector.size(); i++)
{
...
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++