C++字符串数组排序

C++ String array sorting

本文关键字:数组排序 字符串 C++      更新时间:2023-10-16

我在试图从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;
}

算法使用迭代器到序列的开头和末尾。也就是说,你想把std::sort()称为这样的东西:

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

如果您不使用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;
}

编辑:

考虑所有"适当"的命名约定(根据注释):

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

注意:Dietmar Kühl的答案在所有方面都是最好的,std::begin()&std::end()应该用于C++11中类似std::sort的函数,否则可以定义它们。

使用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") 来添加它们

您的循环不会执行任何操作,因为计数器z为0(并且0<0的计算结果为false,因此循环永远不会启动)。

相反,如果您可以访问C++11(您真的应该这样做!),请尝试使用迭代器,例如使用非成员函数std::begin()std::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(begin(name),end(name));
    for(auto n: name){
         cout << n << endl;
    }
    return 0;    
}

实时示例

这对我有效:

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

正如这里的许多人所说,您可以使用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函数中的符号即可。

希望这有帮助:)

干杯!!!

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",
  "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

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

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

程序:

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

  2. 使用排序函数。排序(array_name,array_name+size)

  3. 遍历字符串数组/


代码段

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

我的解决方案与上面的任何解决方案都略有不同,并且与我刚刚运行的解决方案一样有效

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