且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

STL std :: remove(...)在我的主程序中不起作用

更新时间:2023-11-12 09:25:04

您应正确使用函数remove函数的返回值.它将迭代器返回到最后一个未被删除的元素之后的元素:
http://www.cplusplus.com/reference/algorithm/remove [
You should properly use the return from the function remove function. It returns an iterator to the element that follows the last element not removed:
http://www.cplusplus.com/reference/algorithm/remove[^].

Then you need to use the iterator obtained and the str.end() iterator of the original string to pass it to str.erase. So, your code will be fixed is your replace your like using remove and erase with the following line:
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());


这是在此处说明的已知的删除擦除习惯用法的使用: http://en.wikipedia .org/wiki/Erase-remove_idiom [ ^ ].

另请参见: http://en.cppreference.com/w/cpp/algorithm/remove [ ^ ].

但是,这还不是全部.更大的问题(即代码的设计)是这样的:使用您的方法,您将 std::string跳转到字符串的空终止表示,然后返回,这完全是无效的.由于此演示文稿会忘记"字符串的长度,因此以空值结尾的字符串会增加CPU使用率,因此每次使用时,代码都必须不断地由终止符找到它(例如,初始化另一个std::string加上它,这增加了O(N)的时间复杂度的冗余运算.一旦得到std::string,***还是坚持使用它.以此方式更改其签名:


This is the use of the known erase-remove idiom explained here: http://en.wikipedia.org/wiki/Erase-remove_idiom[^].

See also: http://en.cppreference.com/w/cpp/algorithm/remove[^].

However, this is not all. Your problem with the bigger picture — design of your code — is this: with your approach, you would be jumping from std::string to the null-terminated representation of strings and back, which is utterly inefficient. The null-terminated strings adds CPU usage due to the fact that this presentation "forgets" the length of the string, so the code will have to find it by the terminator over and over each time you use it (for example, initialize another std::string with it. This adds a redundant operation of the time complexity of O(N). Once you got an std::string, you should better stay with it. Your function will be more useful if you change its signature in this way:

std::string RemoveSpace(std::string &str) 
// or, optionally, return const std::string
{
    str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
    return str;
}


另请参见:
http://en.wikipedia.org/wiki/Time_complexity [ http://en.wikipedia.org/wiki/Big_O_notation [ http://en.wikipedia.org/wiki/Computational_complexity_theory [

—SA


See also:
http://en.wikipedia.org/wiki/Time_complexity[^],
http://en.wikipedia.org/wiki/Big_O_notation[^],
http://en.wikipedia.org/wiki/Computational_complexity_theory[^].



The first comment to the question by Wes Aday actually presented a correct answer (if you remove the text after '';''). I just did not pay attention for it because, when this comment appeared, I was editing this answer in response to an OP''s follow-up question

—SA