如何建立一个std :: vector< std :: string>然后排序? [英] How can I build a std::vector<std::string> and then sort them?
问题描述
我有一堆字符串,我需要排序。我认为std :: vector将是最简单的方法来做到这一点。但是,我从来没有使用过向量,所以需要一些帮助。
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.
我只需要对它们进行字母数字排序,没有什么特别的。事实上,string :: compare函数会工作。
I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.
之后,我如何迭代它们来验证它们是否排序?
After that, how can I iterate through them to verify that they're sorted?
这里是我到目前为止:
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);
}
推荐答案
p>
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
特别的, std :: string :: compare
不能用作比较器,因为它不会做 sort
要它做的事情:如果第一个参数小于第二个,否则返回false。如果你使用上面的 sort
,它只会使用 operator
使其返回 first.compare(second)< 0
)。
In particular, std::string::compare
couldn't be used as a comparator, because it doesn't do what sort
wants it to do: Return true if the first argument is less than the second, and return false otherwise. If you use sort
like above, it will just use operator<
, which will do exactly that (i.e std::string
makes it return first.compare(second) < 0
).
这篇关于如何建立一个std :: vector< std :: string>然后排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!