首页 > 解决方案 > 占位符变量在迭代期间不更新

问题描述

我正在尝试解决一个在线编码挑战,该挑战要求我在字符串中找到最左边的数字并返回该值。这是预期的:

leftDigit("TrAdE2W1n95!") ➞ 2

leftDigit("V3r1ta$") ➞ 3

leftDigit("U//DertHe1nflu3nC3") ➞ 1

leftDigit("J@v@5cR1PT") ➞ 5

在我的尝试中,我使占位符变量 = 0 来查看值是否正在更新:

int leftDigit(std::string str) {
    int left_most = 0;
    std::vector<int> digits (0,9);
    
    for(int i = 0; i < str.size(); i++){
        if(std::find(digits.begin(), digits.end(), str[i]) != digits.end()){
            left_most = str[i];
            break;
        }
    }
    return left_most;
}

但是,我的代码只通过了 1 次测试,所以问题出在我的逻辑上:

test1
FAILED: Expected: equal to 2
Actual: 0
test2
FAILED: Expected: equal to 3
Actual: 0
test3
FAILED: Expected: equal to 1
Actual: 0
test4
FAILED: Expected: equal to 5
Actual: 0
test5
Test Passed
test6
FAILED: Expected: equal to 8
Actual: 0

更新

根据用户的建议,我进行了以下更改:

int leftDigit(std::string str) {
    char left_most;
    auto pos = str.find_first_of("0123456789");
    
    if(pos == std::string::npos){
        left_most = pos;
    }
    return left_most;
}

但是,输出仍然相同。

标签: c++data-structures

解决方案


Your code fails because you are not populating the vector correctly.

  1. std::vector<int> digits (0,9); declares a vector named digits that contains 0 elements of value 9, which is not what you want. You wanted a vector with 10 elements ranging from 0..9 instead. In C++11 and later, you can create that range using std::vector<int> digits {0,1,2,3,4,5,6,7,8,9}; instead.

  2. Even if you were filling the vector correctly, you are searching for an ASCII character in a vector of integers, so std::find() will always return digits.end(), as 0 does not match '0' (48), 1 does not match '1' (49), etc.

The easiest way to fix the code is to just get rid of the vector altogether:

static const std::string digits = "0123456789";

char leftDigit(const std::string &str) {
    for(int i = 0; i < str.size(); ++i){
        if (digits.find(str[i]) != std::string::npos){
            return str[i];
        }
    }
    return '\0';
}

Alternative, get rid of the loop, too:

#include <algorithm>
#include <cctype>

char leftDigit(const std::string &str) {
    auto iter = std::find_if(str.begin(), str.end(),
        [](char ch){ return std::isdigit(static_cast<unsigned char>(ch)); }
    }
    return (iter != str.end()) ? *iter : '\0';
}

Or simpler:

char leftDigit(const std::string &str) {
    size_t index = str.find_first_of("0123456789");
    return (index != std::string::npos) ? str[index] : '\0';
}

推荐阅读