非标准条件排序算法STL c++
non-standard conditional sort algorithm STL c++
我正在研究STL,并在斯坦福大学的任务中发现了这个非常有趣的PDF。其中一项任务是对歌曲列表进行排序,但这样一来,标记为"我的歌曲"的歌曲总是排在列表的第一位。
所以,如果我们有:
vector <string> song{ "Viva", "Pompeii", "My song", "We remain", "My song", "It is time" };
输出应为:
My song, My song ... (in ascending or descending order);
我用iter_swap
解决了这个问题
这是我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
void print(vector <string> song) {
for (vector <string> ::iterator it = song.begin(), end = song.end(); it != end; ++it) {
cout << *it << " ";
}
}
int main() {
vector <string> song{ "Viva", "Pompeii", "My song", "We remain", "My song", "It is time" };
vector <string> ::iterator start = song.begin();
for (vector <string> ::iterator begin = song.begin(), end = song.end(); begin != end; ++begin){
if (*begin == "My song") {
iter_swap(start, begin);
++start;
}
}
sort(start, song.end());
print(song);
cin.get();
}
但在此之前,我已经挣扎了一段时间,只使用sort
算法来解决这个问题。不幸的是,我没有想出解决办法。你能说是否可以写一个排序函数compare
来解决这个任务吗?我不确定这是否可能,因为sort
只是进行简单的订购。我说得对吗?
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
bool compare(string x, string y) {
// What to write here?
}
void print(vector <string> song) {
for (vector <string> ::iterator it = song.begin(), end = song.end(); it != end; ++it) {
cout << *it << " ";
}
}
int main() {
vector <string> song{ "Viva", "Pompeii", "My song", "We remain", "My song", "It is time" };
sort(start, song.end(), compare);
print(song);
cin.get();
}
是的,这是可能的。您只需要确保字符串"My song"
比任何其他字符串都要小。
bool compare(std::string const& x, std::string const& y)
{
// if y == "My Song", then x can't come before it
if (y == "My song") return false;
// we already know y != "My Song", so if x does, then we know it should come before y
if (x == "My song") return true;
// neither x nor y == "My Song", so just fall back to a normal comparison.
return x < y;
}
顺便说一下,你最初的想法很好。但你所做的只是一个隔断。标准库中也有一个算法。
auto start = std::partition(song.begin(), song.end(),
[](std::string const& s) { return s == "My song"; });
std::sort(start, song.end());
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 在C应用程序中运行C++(带有STL)函数
- 使用2个键的cpp-stl::优先级队列排序不正确
- 在STL容器中使用模板类
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 将stl字符串缩小到小于15个字符的容量
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 在STL - C++中按成绩对学生列表进行排序?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- λ可以适应STL吗?
- 为什么使用 NDK 不能存在不同的 stl 实现?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 在C++中迭代 STL 集时出现奇怪的问题<CStudent>
- 如何在 C++17 STL 并行算法中处理调度?
- 在学习数据结构之前对STL有一个了解是好的吗?
- C++ STL 排序会检查 NaN 吗?