删除字符串算法中的重复项

Tia*_*642 1 c++ string algorithm loops erase

我的作业是删除随机字符串中的重复项。我的想法是使用2个循环来解决问题。

第一个将扫描字符串中的每个字符。第二个将检查字符是否重复。如果是这样,请删除该字符。

string content = "Blah blah..."

    for (int i = 0; i < content.size(); ++i) {
            char check = content.at(i);
            for (int j = i + 1; j < content.size() - 1; ++j) {
                if (check == content.at(j)) {
                    content.erase(content.begin()+j);

                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

问题是它不起作用。它总是删除错误的字符。似乎是索引问题,但我不明白为什么。

临时解决办法是改变content.erase(content.begin()+j);content.erase( remove(content.begin() + i+1, content.end(), check),content.end());

但我认为触发“按值删除”扫描并不是一个好方法。我想用 2 个或更少的循环来完成。

任何想法将不胜感激:)

101*_*010 5

如果可以选择使用 STL,则可以使用 anstd::unordered_set来保留目前看到的字符,并使用 擦除删除习惯用法std::remove_if,如下例所示:

#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>

int main() {
  std::string str("Hello World!");
  std::unordered_set<char> log;
  std::cout << "Before: " << str << std::endl;
  str.erase(std::remove_if(str.begin(), str.end(), [&] (char const c) { return !(log.insert(c).second); }), str.end());
  std::cout << "After:  " << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

现场演示


Vla*_*cow 5

您的循环可能如下所示

#include <iostream>
#include <string>

int main() 
{
    std::string s = "Blah blah...";

    std::cout << '\"' << s << '\"' << std::endl;

    for ( std::string::size_type i = 0; i < s.size(); i++ )
    {
        std::string::size_type j = i + 1;
        while ( j < s.size() )
        {
            if ( s[i] == s[j] )
            {
                s.erase( j, 1 );
            }
            else
            {
                ++j;
            }
        }
    }

    std::cout << '\"' << s << '\"' << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是

"Blah blah..."
"Blah b."
Run Code Online (Sandbox Code Playgroud)

还有许多其他使用标准算法的方法。例如

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main() 
{
    std::string s = "Blah blah...";

    std::cout << '\"' << s << '\"' << std::endl;

    auto last = s.end();

    for ( auto first = s.begin(); first != last; ++first )
    {
        last = std::remove( std::next( first ), last, *first );
    }

    s.erase( last, s.end() );

    std::cout << '\"' << s << '\"' << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出与前面的代码示例相同

"Blah blah..."
"Blah b."
Run Code Online (Sandbox Code Playgroud)