C++ 如何构建 std::vector<std::string> 然后对它们进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/688039/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:45:52  来源:igfitidea点击:

How can I build a std::vector<std::string> and then sort them?

c++stringsortingvector

提问by samoz

I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I've never used vectors before and so would like some help.

我有一堆需要排序的字符串。我认为 std::vector 将是最简单的方法。但是,我以前从未使用过向量,因此需要一些帮助。

I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.

我只需要按字母数字对它们进行排序,没什么特别的。实际上, string::compare 函数会起作用。

After that, how can I iterate through them to verify that they're sorted?

之后,我如何遍历它们以验证它们是否已排序?

Here's what I have so far:

这是我到目前为止所拥有的:

std::sort(data.begin(), data.end(), std::string::compare);

for(std::vector<std::string>::iterator i = data.begin(); i != data.end(); ++i)
{
    printf("%s\n", i.c_str);
}

回答by Johannes Schaub - litb

You can just do

你可以做

std::sort(data.begin(), data.end());

And it will sort your strings. Then go through them checking whether they are in order

它会对你的字符串进行排序。然后通过它们检查它们是否有序

if(names.empty())
    return true; // empty vector sorted correctly
for(std::vector<std::string>::iterator i=names.begin(), j=i+1; 
        j != names.end(); 
        ++i, ++j)
    if(*i > *j)
        return false;
return true; // sort verified

In particular, std::string::comparecouldn't be used as a comparator, because it doesn't do what sortwants it to do: Return true if the first argument is less than the second, and return false otherwise. If you use sortlike above, it will just use operator<, which will do exactly that (i.e std::stringmakes it return first.compare(second) < 0).

特别是,std::string::compare不能用作比较器,因为它没有做sort它想做的事情:如果第一个参数小于第二个参数,则返回 true,否则返回 false。如果你sort像上面那样使用,它只会使用operator<,它会做到这一点(即std::string让它返回first.compare(second) < 0)。

回答by ypnos

What is the question exactly? It seems everything is already there.

究竟是什么问题?似乎一切都已经存在。

However, you should probably use std::cout << *i << std::endl;

但是,您可能应该使用 std::cout << *i << std::endl;

  1. iis an iterator == pointer to the data in the container, so *is needed
  2. c_str()is a function of std::stringand not a variable
  1. i是一个迭代器 == 指向容器中数据的指针,所以*需要
  2. c_str()是函数std::string而不是变量

The problems in your code do not relate to your question?

您代码中的问题与您的问题无关?

Some hints for you:

给你一些提示:

  • std::vectoralso overrides []operator, so you can instead save the iterator hassle and use it like an array (iterate from 0to vector.size()).
  • You could use std::setinstead, which has automatically sorting on insertion (binary tree), so you save the extra sorting.
  • Using a functor makes your output even more fun: copy(V.begin(), V.end(), ostream_iterator<std::string>(cout, "\n"));
  • std::vector还覆盖[]运算符,因此您可以省去迭代器的麻烦并将其用作数组(从0to迭代vector.size())。
  • 您可以std::set改用它,它在插入时自动排序(二叉树),因此您可以节省额外的排序。
  • 使用函子使您的输出更加有趣: copy(V.begin(), V.end(), ostream_iterator<std::string>(cout, "\n"));

回答by bayda

For sort use:
std::sortor std::vector< std::string>::sort(..)method.
To check if it is sorted:
use std::is_sortedfor check is sorted - http://www.sgi.com/tech/stl/is_sorted.html
or
std::adjacent_find( v.begin(), v.end(), std::greater< std::string >() ) == v.end()

用于排序使用:
std::sortstd::vector< std::string>::sort(..)方法。
要检查如果是排序:
使用std::is_sorted用于检查排序- http://www.sgi.com/tech/stl/is_sorted.html

std::adjacent_find( v.begin(), v.end(), std::greater< std::string >() ) == v.end()

for your case you could use default comparator

对于您的情况,您可以使用默认比较器

EDITED:
std::is_sortedis not standard stl function, it defined in sgi stl implementation.
Thanks @Brian Neal for this note.

编辑:
std::is_sorted不是标准的 stl 函数,它在 sgi stl 实现中定义。
感谢@Brian Neal 的这篇笔记。

回答by Mark Ransom

litbis correct, as always.

litb是正确的,一如既往。

I just wanted to point out the more general point - anythingthat can be compared with < can be sorted with std::sort. I'll sometimes sneak an operator< member function into a struct, just so I can do this.

我只是想指出更普遍的一点——任何可以与 < 进行比较的东西都可以用 std::sort 进行排序。我有时会偷偷将 operator< 成员函数放入结构中,这样我就可以做到这一点。

回答by Joe

You could use a std::set, which is naturally a sorted container.

您可以使用 a std::set,它自然是一个已排序的容器。

回答by abe312

Sorting the string:

字符串排序:

using namespace std; // to avoid using std everywhere 
std::sort(data.begin(), data.end()); // this will sort the strings

Checking whether vector is sorted:

检查向量是否已排序:

if(vec.empty())
    return true; // empty vector is sorted correctly
for(std::vector< std::string>::iterator i=vec.begin(), j=i+1; j != vec.end(); ++i, ++j)
    if(*i > *j)  return false;
return true; // sort verified

C++11 Method to check sorted vector:std::is_sorted(vec.begin(),vec.end())

C++11 检查排序向量的方法:std::is_sorted(vec.begin(),vec.end())

Now printing the sorted vector:

现在打印排序向量:

   for(std::vector< std::string>::iterator i = vec.begin(); i != vec.end(); ++i)
{
    std::cout<< *i <<std::endl;
}

回答by Ashish Kapil

Try using comaprator:

尝试使用comaprator:

 #include <cmath>
 #include <cstdio>
 #include <vector>
 #include <iostream>
 #include <algorithm>
 using namespace std;

//comparing function only sorts if string size is equal and keeps the larger integgers at last.
bool myfunction (string i,string j) 
{ 
int n=i.length();
int m=j.length();
if(n==m)
    return (i<j);

return n<m;   
  }


int main() {
int n;
cin>>n;
vector <string> arr(n);
for(int i=0;i<n;i++)
    cin>>arr[i];


sort(arr.begin(),arr.end(),myfunction);

for(int i=0;i<n;i++)
    cout<<arr[i]<<endl;

return 0;
 }