gpt4 book ai didi

c++ - 为什么这条线运行两次并且行为异常?

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:41 25 4
gpt4 key购买 nike

作为序言,我最近才开始自学编程,因此我和他们一样是新手。如果您发现我的代码中有任何不良的一般编码做法(包括与我的问题无关的问题),请告诉我,因为老实说,我可能不知道更好。

关于问题:

我正在尝试编写一小段代码,用新字符串替换出现的目标字符串。我知道存在可以大大改进过程的函数(即查找、替换等),出于练习的目的,我避免使用这些函数并将自己限制为使用迭代器、插入和删除。我也知道还有许多其他地方可以改进代码,我也很乐意对这些部分提出意见,但我主要关心的是我发现的异常行为。我现在拥有的是:

#include <iostream>
#include <string>

bool scan(const std::string, const std::string::iterator);

//replaces occurrences of oldVal in s with newVal
std::string& replace (std::string &s, const std::string &oldVal, const std::string &newVal)
{
std::string::iterator iter = s.begin();
while (iter != s.end()) { //process s
if (scan(oldVal, iter)) { //Checks if characters match
iter = s.erase(iter, iter + oldVal.size()); //deletes occurrence of oldVal
iter = s.insert(iter, newVal.begin(), newVal.end()); //inserts newVal in oldVal's place
iter = iter + newVal.size(); //continues processing after inserted newVal
}
else
++iter; //Move to next character in s to process
}
return s;
}

//This function returns 1 if the strings match and 0 if they do not
bool scan(const std::string target, std::string::iterator iter)
{
for (auto beg = target.begin(); beg != target.end(); ++beg) {
std::cout << "Line 27 " << *iter << " " << *beg << std::endl; //MAIN CONCERN! This line is run twice.
//(It was solely added for debugging. Verifies values being compared)
if (*iter != *beg) {
std::cout << "Condition met; "
<< *iter << " != " << *beg << std::endl; //added for debugging. Double verifies values post-comparison
return 0;
}
++iter;
++beg;
}
return 1;
}

int main()
{
std::string mainStr, oldStr, newStr;
std::getline(std::cin, mainStr); //Overall it'd be better for s to be a list of strings, but my concern is with line 27
std::cin.clear();
std::cin >> oldStr >> newStr;
std::cout << "Output: " << replace(mainStr, oldStr, newStr) << std::endl; //Prints post-replacement string
}

似乎正在发生的是第 27 行 (std::cout << "Line 27 "...) 在第一次调用扫描时执行了两次。例如,给定输入:

tho
tho though

我得到了输出(//是我在运行之外添加的评论,即仅针对这篇文章)

Line 27 t t //This part is run twice and does weird things
Line 27 h o //If it was just incrementing it should read "Line 27 h h"
Condition met; h != o //This shouldn't happen; The condition should have tested t != t
Line 27 h t //It's seems fine from this point onwards
Condition failed; h != t
Line 27 o t
Condition failed; o != t
Output: tho

这可能是什么原因?

谢谢!

最佳答案

我发现的一个错误:在 scan() 中,beg 迭代器在每次迭代中增加两次,因为 ++begfor(...) 循环行和 beg++ 在循环的末尾。

关于c++ - 为什么这条线运行两次并且行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26774562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com