首页 > 解决方案 > 遍历向量以获得搜索功能

问题描述

我有一个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;

标签: c++

解决方案


您的函数有一个导致未定义行为的错误和两个显示缺乏清晰度的构造。

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,那么我能想到的有两件事可以解释这种行为。

  1. 8 是 中的第一项v
  2. 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;
}

通过这种更改,无需将空向量与非空向量区别对待。


推荐阅读