gpt4 book ai didi

c++如何对位集 vector 进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:20 29 4
gpt4 key购买 nike

我有一个 bitsets vector :

vector < bitset<1024> > myvector;

从以下位置对该 vector 进行排序的最佳方法是什么:

0: xxx0100
1: xxx1100
2: xxx0010
3: xxx0001
...
...

此订单:

0: xxx0001
1: xxx0010
2: xxx0100
3: xxx1100
...
...

我已经尝试使用 std:sort 执行此操作,但没有成功,因为 std:sort 使用“<”- 运算符,它不适用于位集。

在此先感谢您的帮助!非常感谢任何建议或想法!

编辑:
我的问题与 Sorting a vector of custom objects 不同,因为不可能对 bitset 使用“<”- 运算符。所以我的问题是,我可以使用哪个运算符来比较 bitset

最佳答案

一种对 std::bitset 进行排序的简单方法将其转换为 std::string使用 std::bitset::to_string 然后使用 std::string s operator<比较位集。

std::vector<std::bitset<128>> data = {1000,2000,80000,15,6000,2};
std::sort(data.begin(), data.end(), [](const auto & lhs, const auto & rhs)
{ return lhs.to_string() < rhs.to_string(); });

Live Example

正如评论中所指出的,如果 bitset 足够小以适合 unsigned long long那么你可以使用 std::bitset::to_ullong 并比较 unsigned long long s 而不是字符串。

关于c++如何对位集 vector 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33302286/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com