一行断言来测试 STL 容器是否已排序

发布于 2024-09-04 01:08:07 字数 88 浏览 1 评论 0原文

有没有一种方法可以编写一个单行条件,如果 STL 容器已排序,该条件将返回 true?有问题的容器是 std::vector

我打算在断言中使用它

Is there a way to write a one line condition that would return true if STL container is sorted? The container in question is std::vector

I intend to use it in an assert

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧城空念 2024-09-11 01:08:07

adjacent_find 与较小或较大函子结合使用。

限制:
您应该知道容器是按升序还是降序排序。

如果向量应该按升序排序:

//Checks the first element where adjacent value where elem > nextElem
//returns end if the vector is sorted!
//Complexity is O(n)
vector<int>::iterator pos =  std::adjacent_find (aVec.begin(), aVec.end(),   // range
                                     std::greater<int>());               


if (pos == aVec.end()) 
{
    std::cout<<" sorted"<<endl;
}
else
{
    std::cout<<"Not sorted"<<endl;
}

Use adjacent_find in combination with less or greater functor.

Restriction:
You should know whether the container is sorted in ascending or descending.

If the vector is supposed to be sorted in ascending order:

//Checks the first element where adjacent value where elem > nextElem
//returns end if the vector is sorted!
//Complexity is O(n)
vector<int>::iterator pos =  std::adjacent_find (aVec.begin(), aVec.end(),   // range
                                     std::greater<int>());               


if (pos == aVec.end()) 
{
    std::cout<<" sorted"<<endl;
}
else
{
    std::cout<<"Not sorted"<<endl;
}
贩梦商人 2024-09-11 01:08:07

您可以使用 std::is_sorted(vec.begin(),vec. end()) 来测试它是否已排序。但请注意,这是 O(n)。

You can use std::is_sorted(vec.begin(),vec.end()) to test if it is sorted. Note, though, that this is O(n).

守望孤独 2024-09-11 01:08:07

这取决于您要使用哪种 STL 数据类型。

如果键已重载比较运算符,则映射已按键排序。你去这里真好。

列表要求您显式调用排序函数。您需要跟踪是否已对其进行排序。

希望这有帮助。

It depends what STL data type you want to use.

A map is already sorted by the key provided the key has overloaded compare operators. You're good to go here.

A list requires that you explicitly call the sort function. You will need to keep track of whether or not you sorted it yet.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文