c++ - 占位符变量在迭代期间不更新
问题描述
我正在尝试解决一个在线编码挑战,该挑战要求我在字符串中找到最左边的数字并返回该值。这是预期的:
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;
}
但是,输出仍然相同。
解决方案
Your code fails because you are not populating the vector
correctly.
std::vector<int> digits (0,9);
declares avector
nameddigits
that contains 0 elements of value9
, which is not what you want. You wanted avector
with 10 elements ranging from0..9
instead. In C++11 and later, you can create that range usingstd::vector<int> digits {0,1,2,3,4,5,6,7,8,9};
instead.Even if you were filling the
vector
correctly, you are searching for an ASCII character in avector
of integers, sostd::find()
will always returndigits.end()
, as0
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';
}
推荐阅读
- camunda - Camunda Modeler 没有高级模式按钮
- flutter - 如何创建具有内阴影和渐变填充的卡片
- reactjs - 对于 React 项目,@emotion/react 比 @emotion/css 有什么好处?
- python - 尝试导入时没有名为“PyPDF2”的模块
- apache - Htaccess 将子文件夹重写为子域
- python - 在 gcloud -django 上上传图片时没有名为“config”的模块
- sapui5 - 预期为 '}' 而在表达式中看到 '='
- java - 使用 Canvas 正确绘制点
- cordova - 科尔多瓦 - 状态栏中的图像
- scala - 如何在 play framework 2.5 中将 DBApi 注入到 trait 组件中?