设为首页 加入收藏

TOP

[C++]对字符串向量排序
2015-11-21 01:00:11 来源: 作者: 【 】 浏览:2
Tags:字符串 向量 排序

让字符串向量首先按字符串长度进行排序,长度短的在前,长的在后。如果长度相等则按字典序排序,并移除重复的字符串。

去重复并按字典序排序:

?

void elimDumps(vector
  
    &words)
{
	// 按字典序排序
	sort(words.begin(), words.end());

	// unique重排输入范围,使得每个单词只出现一次
	// 并排列在范围的前部,返回指向不重复区域之后一个位置的迭代器
	auto end_unique = unique(words.begin(), words.end());

	// 删除重复单词
	words.erase(end_unique, words.end());
}
  

比较函数,用来按长度排序单词:

?

?

bool isShorter(const string &s1, const string &s2)
{
	return s1.size() < s2.size();
}

主函数:

?

?

int _tmain(int argc, _TCHAR* argv[])
{
	// 创建并初始化字符串向量
	vector
  
    words{ "aaa", "c", "eeee", "b", "cccc", "c" };

	// 移除重复单词并按字典序排序
	elimDumps(words);

	// 将向量按字符串大小排序,使用稳定排序算法保持相同长度的单词按字典序排列
	stable_sort(words.begin(), words.end(), isShorter);

	for (auto &s : words)
	{
		cout << s << endl;
	}

	return 0;
}
  

程序执行结果:

?

\

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Form.ShowDialog(this) 下一篇在CentOS上使用Neatbeans开发C++..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: