C++ 使用 STL 对字符串进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25167599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a string using STL
提问by c_coder
I am trying to sort the characters of a string using C++ STL
and came up with this code.
我正在尝试使用C++ STL
此代码对字符串的字符进行排序。
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
using namespace std;
vector<string>::iterator it;
string arr[] = {"jajajaj"};
vector<string> v(arr, arr+2);
sort(v.begin(), v.end());
for (it=v.begin(); it<v.end(); it++) {
cout << *it;
}
return 0;
}
But unfortunately its not sorting properly when the array contains single element. How to do it using STL. Please help.
但不幸的是,当数组包含单个元素时,它没有正确排序。如何使用 STL 做到这一点。请帮忙。
回答by quantdev
If you need a string, use a std::string
:
如果您需要一个字符串,请使用std::string
:
(I used a for-range loop to make the code cleaner)
(我使用了 for-range 循环来使代码更清晰)
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string s = {"jajajaj"};
sort(s.begin(), s.end());
for (auto c : s)
cout << c;
return 0;
}
Outputs:
输出:
aaajjjj
啊啊啊啊啊啊啊啊
Note:
笔记:
Your current code is not working because, as commented, you create a vector of size 2 out of an array of size 1, which has undefined behavior.
您当前的代码不起作用,因为正如所评论的,您从大小为 1 的数组中创建了一个大小为 2 的向量,该向量具有未定义的行为。
回答by Vikas Gupta
You can directly sort the string.
您可以直接对字符串进行排序。
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str = "jajajaj";
sort(str.begin(), str.end());
cout << str;
return 0;
}
Hope this might be helpful.
希望这可能会有所帮助。
回答by James Curran
You seem to be confusing a std::string
with an array of chars.
您似乎将 astd::string
与字符数组混淆了。
int main()
{
using namespace std;
string arr = "jajajaj";
vector<char> v(arr.begin(), arr.end());
sort(v.begin(), v.end());
vector<char>::iterator it;
for (it=v.begin(); it<v.end(); ++it) {
cout << *it;
}
return 0;
}
I haven't tested that, but it should work....
我还没有测试过,但它应该工作......
UPDATE:
更新:
Alternately, we could just sort the string's character directly: (Thanks guys!)
或者,我们可以直接对字符串的字符进行排序:(谢谢大家!)
int main()
{
using namespace std;
string arr = "jajajaj";
sort(arr.begin(), arr.end());
cout << arr;
return 0;
}
回答by rashedcs
回答by Piyush Garg
In order to sort a string, just input string from the user and use the sort() in STL for it.
为了对字符串进行排序,只需从用户输入字符串并使用 STL 中的 sort() 即可。
#include<bits/stdc++.h>
using namespace std;
int main()
{
string arr;
cin >>arr;
sort(arr.begin(), arr.end());
cout <<arr;
}
See the sample image below for the output with input string as "Michael".
有关输入字符串为“Michael”的输出,请参见下面的示例图像。