【问题标题】:Is it possiblle to Implement next_permutation() on a STL set<t>是否可以在 STL set<t> 上实现下一个 permutation()
【发布时间】:2016-02-20 23:25:09
【问题描述】:

鉴于这一套

   set<string> s = {"a","b","c"};

是否可以实现 next_permutation() 来获取所有组合,其中不重复的元素和顺序很重要?

【问题讨论】:

  • 您不会对std::set 中的元素重新排序。这是一个有根据的问题吗?
  • 我正在尝试获取该集合的所有组合。不将数据发送回集合。
  • "std::set 是一个关联容器,其中包含一组排序后的 Key 类型的唯一对象。" 来自cppreference 几乎总结了这一点。了解您的容器。
  • 我不是在问如何以不同的顺序将集合重写为集合。我在问“是否可以在 STL 集 上实现 next_permutation()”,而不是按照您的建议创建重新排列集。

标签: c++ stl permutation


【解决方案1】:

不,这是不可能的。 std::set 是一个关联容器并保持严格的弱排序。 std::next_permutation 转换它给定的范围,这会破坏排序。

如果您需要获取set 内容的排列,我建议您使用std::vector。您可以将集合复制到向量中,然后从中获取排列。

std::set<int> set_data;
//fill set
std::vector<int> temp(set_data.begin(), set_data.end());
do
{
    // code goes here
}
while(std::next_permutation(temp.begin(), temp.end()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多