C ++字符串数组排序

时间:2013-08-17 19:36:47

标签: c++ arrays sorting

我在尝试从C ++库中找出排序函数并尝试从a-z对这个字符串数组进行排序时遇到了很多麻烦,请帮助!

我被告知要使用它,但我无法弄清楚我做错了什么。

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

9 个答案:

答案 0 :(得分:27)

算法使用迭代器到序列的开头和结尾。也就是说,您想要调用std::sort()这样的内容:

std::sort(std::begin(name), std::end(name));

如果你不使用C ++ 11并且你没有std::begin()std::end(),他们很容易自己定义(显然不在命名空间{{1} }}):

std

答案 1 :(得分:11)

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

修改:

考虑所有“正确”的命名约定(根据评论):

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

注意:DietmarKühl的答案最好,std::begin()&amp; std::end()应该与{+ 1}}类似的函数用于C ++ 11,否则可以定义它们。

答案 2 :(得分:8)

使用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

这完全避免使用普通数组,并允许您使用std :: sort函数。您可能需要更新编译器以使用= {...}您可以使用vector.push_back("name")

来添加它们

答案 3 :(得分:4)

你的循环没有做任何事情,因为你的计数器z是0(0 <0评估为false,所以循环永远不会开始)。

相反,如果你有权访问C ++ 11(你真的应该以此为目标!)尝试使用迭代器,例如:通过使用非成员函数std::begin()std::end(),以及范围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

答案 4 :(得分:2)

这对我有用:

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

答案 5 :(得分:2)

正如许多人所说,你可以使用std :: sort进行排序,但是当你例如想要从z-a排序时会发生什么?这段代码可能很有用

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 

}

如果要颠倒排序顺序,只需修改cmp函数中的符号。

希望这有用:)

干杯!!!

答案 6 :(得分:1)

多集合容器使用红黑树来保持元素排序。

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

示例输出:

Adam
Adam
Adam
Fred
Fred
Jack
Jess
Jesse
Jill
Joe
Mark
Phil
Susie
Zeke

注意,优点是多重插入在插入和删除后保持排序,非常适合显示活动连接或不显示。

答案 7 :(得分:0)

  

我们可以使用sort()函数对字符串数组进行排序。

程序:

  1. 首先确定大小字符串数组。

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

  3. 通过字符串数组/

  4. 进行迭代

    代码段

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

答案 8 :(得分:-2)

我的解决方案与上述任何一种解决方案略有不同,因为我刚刚运行它。因此感兴趣:

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