C++ Erase not working as expected
In your C++ program, you’re using std::remove
from the
header to remove tabs from a string. However, std::remove
doesn’t actually erase elements from the container. Instead, it moves all elements that are not equal to the given value to the front of the container and returns an iterator to the new end of the range containing the non-removed elements. The elements after this iterator are in an unspecified state.
To fix the issue and remove the unwanted characters, you should use the erase-remove
idiom. This idiom combines the remove
algorithm with the erase
member function of the container to actually remove the elements from the container.
-
تعامل مع تجميع البيانات في C#20/03/2024
-
حلول أخطاء إنشاء قواعد بيانات Django24/03/2024
Here’s how you can modify your code to use the erase-remove
idiom:
cpp#include
#include
#include // std::remove
int main()
{
std::string str("This is an example sentence blah");
str.erase(std::remove(str.begin(), str.end(), '\t'), str.end());
std::cout << str;
return 0;
}
In this modified code, std::remove
is used to move all non-tab characters to the front of the string, and then str.erase
is used to erase the characters from the first occurrence of the tab to the end of the string.
This should give you the expected output:
This isanexample sentence blah
Using the erase-remove
idiom ensures that the unwanted characters are actually removed from the string, rather than just moved to the end.
المزيد من المعلومات
بالفعل، لاحظت في البرنامج الذي قدمته أنك تقوم باستخدام دالة std::remove
من أجل إزالة الأحرف \t
من السلسلة، ومع ذلك، هذه الدالة لا تقوم بإزالة الأحرف فعلياً، بل تقوم بنقل الأحرف التي ليست \t
إلى أمام السلسلة، وتعيد مؤشراً إلى نهاية النطاق الجديد الذي يحتوي على العناصر التي لم يتم إزالتها. العناصر بعد هذا المؤشر في حالة غير محددة.
لحل هذه المشكلة وإزالة الأحرف غير المرغوب فيها، يجب عليك استخدام “طريقة الإزالة والنقل” (erase-remove idiom
). هذه الطريقة تجمع بين خوارزمية remove
مع دالة erase
لحاوية البيانات من أجل إزالة العناصر فعلياً من الحاوية.
فيما يلي كيفية تعديل البرنامج الخاص بك لاستخدام طريقة الإزالة والنقل:
cpp#include
#include
#include // std::remove
int main()
{
std::string str("This is an example sentence blah");
str.erase(std::remove(str.begin(), str.end(), '\t'), str.end());
std::cout << str;
return 0;
}
في هذا الكود المعدل، يتم استخدام std::remove
لنقل جميع الأحرف غير \t
إلى أمام السلسلة، ثم يتم استخدام str.erase
لإزالة الأحرف من أول حرف \t
وحتى نهاية السلسلة.
هذا يجب أن يعطيك الناتج المتوقع:
This isanexample sentence blah
باستخدام طريقة الإزالة والنقل، يتم التأكد من إزالة الأحرف غير المرغوب فيها من السلسلة، بدلاً من نقلها إلى النهاية.