【发布时间】:2015-03-29 09:28:49
【问题描述】:
我正在学习 STL,并发现了来自斯坦福的 this 非常有趣的 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();
}
【问题讨论】: