c++ - 将唯一值左移并删除字符串中的重复值

标签 c++

我正在尝试编写一个函数,该函数采用字符串中的唯一值,将它们一起向左移动,然后将重复的值设置为空字符串。我希望我的函数返回有多少值被更改为空字符串。

我的数组是 { "cindy", "sasha", "cindy", "daisy", "bear", "bear", "bear"};但我的代码似乎跳过了“熊”一次,只返回 2。

例如,我不能这样做

int duplicaterase(string array[], int  n)
{
const auto end = array + n;
auto finish = end;
for (auto start = array; start != finish; ++start) {
    finish = std::remove(start+1, finish, *start);
}
std::fill(finish, end, std::string());
return static_cast<int>(end - finish);;
}

最佳答案

这可以简单地使用 remove 来完成在 for 循环中:

auto finish = end(duplicates1);

for(auto start = begin(duplicates1); start != finish; ++start) finish = remove(next(start), finish, *start);
fill(finish, end(duplicates1), string());

Live Example


上述解决方案保留了顺序,但真正最快的解决方案是排序并使用unique :

sort(begin(duplicates1), end(duplicates1));
fill(unique(begin(duplicates1), end(duplicates1)), end(duplicates1), string());

Live Example

关于c++ - 将唯一值左移并删除字符串中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837827/

相关文章:

C++ 多个大文件在一个二进制文件中

c++ - 评估顺序 >> 和 [++]

c++ - 如果 extern "C"包含与 Qt 库冲突怎么办?

c++ - 如何反转文件中行的顺序

c++ - 对象静态成员的初始化

c++ - 内联代码应该有多小

c++ - 赋值运算符重载和自赋值

java - 内存分配究竟是如何进行的,Java 和 C 如何交互以跟踪同一个对象?

c++ - 为什么要在方法的定义中使用 throw?

c++ - 优化条件的方法 "if (m == 0 || n == 0)"