c++ - 遍历向量以获得搜索功能
问题描述
我有一个vector<int>
我需要搜索给定值val
然后返回该i
值第一次出现的索引。如果向量是空的,它应该返回常量EMPTY_VEC
这就是我到目前为止所拥有的。
const int EMPTY_VEC = std::numeric_limits<int>::max();
size_t find(const std::vector<int>& v, int val)
{
for(int i = 0; i < v.size(); ++i) {
if(v[i] == val) {
return i;
break;
} else if(v.size() == 0) {
return EMPTY_VEC;
}
}}
当我调用这个函数时,它每次都返回 0。
它可能与我的向量的定义方式有关吗?
uint32_t seed = std::chrono::system_clock::now().time_since_epoch().count();
// uint32_t is a type that is guaranteed to be 32 bits wide (unlike int or unsigned int)
// seed is the pseudorandom value returned from the system clock object (like time(0))
std::minstd_rand gen(seed);
// gen is the object responsible for creating the random numbers
std::uniform_int_distribution<int> dist(0,BIGGEST_RANDOM);
// choose random ints between 0 and BIGGEST_INT
// OK, stop ignoring now
std::vector<int> data {};
for (size_t i = 0; i < DATA_SIZE; ++i)
{
data.push_back(dist(gen)); // dist(gen) is the random int
}`
std::cout << find(data, 8) << std::endl;
解决方案
您的函数有一个导致未定义行为的错误和两个显示缺乏清晰度的构造。
size_t find(const std::vector<int>& v, int val)
{
for(int i = 0; i < v.size(); ++i) {
if(v[i] == val) {
return i;
// Lack of clarity.
// The function will never hit this line.
// The return statement above will ensure that.
break;
}
// Lack of clarity.
// This else block will never be executed.
// You will enter the for loop only when v is not empty.
// Hence, the conditional will always evaluate to false.
else if(v.size() == 0) {
return EMPTY_VEC;
}
}
// Error.
// Missing return statement. This causes undefined behavior.
}
如果您注意到该函数每次都返回 0,那么我能想到的有两件事可以解释这种行为。
- 8 是 中的第一项
v
。 - 8 从未在
v
.return
即使没有语句,该函数在到达函数末尾时也恰好返回 0 。请注意,这只是未定义行为的标志。不要依赖那个值。
我认为将返回类型更改为int
. 如果找到该项目,您可以返回一个有效的索引,如果没有找到该项目,则返回 -1。当输入向量为空时返回std::numeric_limits<int>::max()
听起来不正确。
int find(const std::vector<int>& v, int val)
{
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] == val) {
return i;
}
}
// Item not found. Return -1.
return -1;
}
通过这种更改,无需将空向量与非空向量区别对待。
推荐阅读
- c# - 如何对绑定到不是显示成员的 UltraComboEditor 的列进行排序
- android - 使用 jetpack 从 ViewPager2 导航到另一个片段
- python - 使用 paramiko ssh 进入远程并以不同用户身份运行命令
- unity3d - Unity Editor 2019.3.0f6 上的 Oculus Quest 无法调试
- r - 将向量汇总到某个分位数的R方法
- hl7-fhir - 如何使用_content在fhir中搜索birthData?
- javascript - 如何在javascript中舍入一个整数
- python-3.x - 向外部服务器发出 POST 请求时出现 SSL 证书错误
- google-chrome - InboxSDK 获取线程中的所有附件
- sql - 连接 VarChar 和日期字段