占位符变量在迭代过程中不更新

oo92

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

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;
}

但是,输出仍然相同。

雷米·勒博

您的代码失败,因为您没有vector正确填充

  1. std::vector<int> digits (0,9);声明一个包含0个value元素的vectornamed ,这不是您想要的。您想要一个包含10个元素的,而不是。在C ++ 11和更高版本中,您可以改用创建该范围digits9vector0..9std::vector<int> digits {0,1,2,3,4,5,6,7,8,9};

  2. 即使您vector输入的字符正确无误,也要搜索vector整数形式的ASCII字符,因此std::find()始终会返回digits.end(),如0不匹配'0'48),1不匹配'1'49)等。

修复代码的最简单方法是vector完全摆脱

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';
}

或者,也摆脱循环:

#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';
}

或更简单:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章