C++ 字符串数组排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18292619/
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
C++ String array sorting
提问by ssj3goku878
I am having so much trouble trying to figure out the sort function from the C++ library and trying to sort this array of strings from a-z , help please!!
我在尝试从 C++ 库中找出排序函数并尝试从 az 中对这个字符串数组进行排序时遇到了很多麻烦,请帮忙!!
I was told to use this but I cant figure out what I am doing wrong.
我被告知要使用它,但我无法弄清楚我做错了什么。
// std::sort(stringarray.begin(), stringarray.end());
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int z = 0;
string name[] = {"john", "bobby", "dear",
"test1", "catherine", "nomi",
"shinta", "martin", "abe",
"may", "zeno", "zack", "angeal", "gabby"};
sort(name[0],name[z]);
for(int y = 0; y < z; y++)
{
cout << name[z] << endl;
}
return 0;
}
采纳答案by P0W
int z = sizeof(name)/sizeof(name[0]); //Get the array size
sort(name,name+z); //Use the start and end like this
for(int y = 0; y < z; y++){
cout << name[y] << endl;
}
Edit :
编辑 :
Considering all "proper" naming conventions (as per comments) :
考虑到所有“正确”的命名约定(根据评论):
int N = sizeof(name)/sizeof(name[0]); //Get the array size
sort(name,name+N); //Use the start and end like this
for(int i = 0; i < N; i++){
cout << name[i] << endl;
}
Note:Dietmar Kühl's answer is best in all respect, std::begin()
& std::end()
should be used for std::sort
like functions with C++11, else they can be defined.
注意:Dietmar Kühl 的回答在所有方面都是最好的,std::begin()
&std::end()
应该用于std::sort
C++11 中的类似函数,否则它们可以被定义。
回答by Dietmar Kühl
The algorithms use iterator to the beginning and past the end of the sequence. That is, you want to call std::sort()
something like this:
算法使用迭代器到序列的开头和结尾。也就是说,你想调用std::sort()
这样的东西:
std::sort(std::begin(name), std::end(name));
In case you don't use C++11 and you don't have std::begin()
and std::end()
, they are easy to define yourself (obviously not in namespace std
):
如果您不使用 C++11 并且您没有std::begin()
and std::end()
,它们很容易定义自己(显然不在 namespace 中std
):
template <typename T, std::size_t Size>
T* begin(T (&array)[Size]) {
return array;
}
template <typename T, std::size_t Size>
T* end(T (&array)[Size]) {
return array + Size;
}
回答by olevegard
Example using std::vector
使用 std::vector 的示例
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
这完全避免了使用普通数组,并允许您使用 std::sort 函数。您可能需要更新编译器以= {...}
使用vector.push_back("name")
回答by TemplateRex
Your loop does not do anything because your counter z
is 0 (and 0 < 0 evaluates to false
, so the loop never starts).
您的循环不会执行任何操作,因为您的计数器z
为 0(并且 0 < 0 的计算结果为false
,因此循环永远不会开始)。
Instead, if you have access to C++11 (and you really should aim for that!) try to use iterators, e.g. by using the non-member function std::begin()
and std::end()
, and a range-for loop to display the result:
相反,如果您可以访问 C++11(并且您确实应该以此为目标!)尝试使用迭代器,例如通过使用非成员函数std::begin()
andstd::end()
和 range-for 循环来显示结果:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int z = 0;
string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
sort(begin(name),end(name));
for(auto n: name){
cout << n << endl;
}
return 0;
}
回答by lpapp
This works for me:
这对我有用:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
int sname = sizeof(name)/sizeof(name[0]);
sort(name, name + sname);
for(int i = 0; i < sname; ++i)
cout << name[i] << endl;
return 0;
}
回答by nelt22
As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful
正如这里的许多人所说,您可以使用 std::sort 进行排序,但是例如,当您想要从 za 进行排序时会发生什么?此代码可能有用
bool cmp(string a, string b)
{
if(a.compare(b) > 0)
return true;
else
return false;
}
int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);
for(int i = 0; i < length; i++)
cout << words[i] << " ";
cout << endl;
// output will be: this test is a
}
If you want to reverse the order of sorting just modify the sign in the cmp function.
如果要颠倒排序顺序,只需修改 cmp 函数中的符号即可。
Hope this is helpful :)
希望这有帮助:)
Cheers!!!
干杯!!!
回答by zettix
The multiset container uses a red-black tree to keep elements sorted.
multiset 容器使用红黑树来保持元素排序。
// using the multiset container to sort a list of strings.
#include <iostream>
#include <set>
#include <string>
#include <vector>
std::vector<std::string> people = {
"Joe",
"Adam",
"Mark",
"Jesse",
"Jess",
"Fred",
"Susie",
"Jill",
"Fred", // two freds.
"Adam",
"Hyman",
"Adam", // three adams.
"Zeke",
"Phil"};
int main(int argc, char **argv) {
std::multiset<std::string> g(people.begin(), people.end()); // """sort"""
std::vector<std::string> all_sorted (g.begin(), g.end());
for (int i = 0; i < all_sorted.size(); i++) {
std::cout << all_sorted[i] << std::endl;
}
}
Sample Output:
示例输出:
Adam
Adam
Adam
Fred
Fred
Hyman
Jess
Jesse
Jill
Joe
Mark
Phil
Susie
Zeke
Note the advantage is that the multiset stays sorted after insertions and deletions, great for displaying say active connections or what not.
请注意,优点是多重集在插入和删除后保持排序,非常适合显示活动连接或其他内容。
回答by rashedcs
We can sort() function to sort string array.
我们可以通过 sort() 函数对字符串数组进行排序。
Procedure :
程序 :
At first determine the size string array.
use sort function . sort(array_name, array_name+size)
Iterate through string array/
首先确定大小字符串数组。
使用排序功能。排序(数组名称,数组名称+大小)
遍历字符串数组/
Code Snippet
代码片段
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
int len = sizeof(name)/sizeof(name[0]);
sort(name, name+len);
for(string n: name)
{
cout<<n<<" ";
}
cout<<endl;
return 0;
}
回答by David Elliman
My solution is slightly different to any of those above and works as I just ran it.So for interest:
我的解决方案与上面的任何一个都略有不同,并且在我刚刚运行它时有效。所以感兴趣:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
char *name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
vector<string> v(name, name + 14);
sort(v.begin(),v.end());
for(vector<string>::const_iterator i = v.begin(); i != v.end(); ++i) cout << *i << ' ';
return 0;
}