C ++字符串数组排序 [英] C++ String array sorting

查看:78
本文介绍了C ++字符串数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有人告诉我要使用它,但我无法弄清楚我在做什么错.

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

推荐答案

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

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

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

注意:DietmarKühl的答案在各个方面都是最好的, std :: begin()&应该将 std :: end()用于 std :: sort ,例如C ++ 11中的函数,否则可以对其进行定义.

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.

这篇关于C ++字符串数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆