简体   繁体   English

C ++字符串数组排序

[英]C++ String array sorting

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 az , 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;
}

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()std::end() ,则很容易自己定义(显然不在命名空间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;
}
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. 注意: DietmarKühl的答案在所有方面都是最好的, std::begin()std::end()应该用于与C ++ 11一样的std::sort函数,否则可以定义它们。

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;

}

http://ideone.com/Q9Ew2l http://ideone.com/Q9Ew2l

This completely avoids using plain arrays, and lets you use the std::sort function. 这完全避免使用普通数组,并允许您使用std :: sort函数。 You might need to update you compiler to use the = {...} You can instead add them by using vector.push_back("name") 您可能需要更新编译器以使用= {...}您可以使用vector.push_back("name")来添加它们

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, eg by using the non-member function std::begin() and std::end() , and a range-for loop to display the result: 相反,如果你有权访问C ++ 11(你真的应该瞄准它!)尝试使用迭代器,例如使用非成员函数std::begin()std::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;    
}

Live example . 实例

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;
}

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 za? 正如许多人已经说过的那样,你可以使用std :: sort进行排序,但是当你例如想从za中排序时会发生什么? This code may be useful 此代码可能很有用

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!!! 干杯!!!

The multiset container uses a red-black tree to keep elements sorted. 多集合容器使用红黑树来保持元素排序。

// 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",
  "Jack",
  "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
Jack
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. 注意,优点是多插槽在插入和删除后保持排序,非常适合显示说活动连接或不显示。

We can sort() function to sort string array. 我们可以使用sort()函数对字符串数组进行排序。

Procedure : 程序:

  1. At first determine the size string array. 首先确定大小字符串数组。

  2. use sort function . 使用排序功能。 sort(array_name, array_name+size) sort(array_name,array_name + size)

  3. 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;
}

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM