2016-05-15 95 views
-5
#include <iostream> 
#include <array> 
#include <algorithm> 
#include <cstring> 

using namespace std; 

int main() { 
    array<char, 20> test{"HelloWorld"}, tmp; 

    // method 1 
    tmp = test; 
    sort(tmp.begin(), tmp.begin() + strlen(tmp.begin())); 
    cout << "result: " << tmp.data() << endl; 

    // method 2 
    tmp = test; 
    sort(tmp.begin(), tmp.end()); 
    cout << "result: " << tmp.data() << endl; 

    return 0; 
} 

std::array可以用方法1进行排序。但它很难看。如何使用std :: sort对std :: array进行排序?

我更喜欢方法2,但什么都不能返回。它出什么问题了?

+1

这两个'sort'调用做不同的事情。使用你需要的那个。 –

+3

这里的根本问题是你试图让'std :: array'成为'std :: string'。这不是,而且试图用它作为一个永远不会很好的工作。 –

+0

为什么不使用'std :: string'?然后方法2将正常工作。 –

回答

4

第二种方法是将所有的\0元素排序到前面。 (他们比任何其他字符少

当你试着和.data()打印你得到一个char const*对象返回其在流类是像一个C字符串处理。这是一个空结束的字符串由于第一个字符是空不打印输出。

您可以用

auto cmp = [](char a, char b) { return a != '\0' && a<b; } 
    sort(tmp.begin(), tmp.end(), cmp); 

解决这个使用其在最后排序\0比较。

但正如Jerry Coffin在评论中所说,std::array不是std::string - 使用符合您需要的那个(在这种情况下可能为std::string)。

+0

@LokiAstari:谢谢你的加入 - 那会好很多。 –

2

您正在打印一个C字符串,该字符串依赖于终止空字符的存在:\0
当您对整个数组进行排序时,将该空字符移动到前面,这会告诉打印函数它是一个空字符串。

因此,你别无选择,只能使用丑陋的版本。话虽这么说,这里是写它,你可能更喜欢一个更安全的方式:

sort(tmp.begin(), find(tmp.begin(), tmp.end(), '\0')); 
+0

不知道如何更干净。 –

+0

@BenjaminLindley'tmp.begin()+ strlen(tmp.begin())'做了额外的工作。 –

+0

那是什么工作?如果我不得不猜测哪一个能够做更多的工作,那么它就是你的版本,因为它需要比较迭代器本身(到最终迭代器)的值以及取消引用的值(到0)。而'strlen'只检查解除引用的值。 –

-2

,你可以把它写这样sort(tmp.begin(), tmp.end());

tmp.begin():返回一个迭代器到开始。
tmp.end():返回一个迭代器到最后。

他们是(公共成员函数)

+0

这正是OP在方法2中所说的,但结果并不如人意。 –