c++ - 常量迭代器的问题

标签 c++ c++11 iterator

我正在尝试编写一个模板函数,它接受一个序列(通过 2 个迭代器)并计算该序列的排列数,其中没有连续的相同元素。 我就是这么做的

    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/

如果我传递 const 迭代器,此代码将不起作用。我应该更改什么以使其与 const 迭代器一起使用?

最佳答案

This code not working if i pass const iterators. What should I change to make it work with const iterators?

您不能:std::next_permutation() 修改值,因此与 const 迭代器不兼容。

-- 编辑 --

OP 询问

How can i implement this function in right way?

我建议您遵循 Jarod42 的建议:复制一份。

我建议如下

template <class Container>
size_t count_perm (Container c)  // note: c is a copy
{
    if ( c.cbegin() == c.cend() )
        return 1;

    size_t count = 0U;

    std::sort(c.begin(), c.end());

    if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend()))
     {
       std::size_t ui = c.size();

       for ( count = ui ; --ui > 1 ; count *= ui )
        ; 

       // count now is c.size() ! (factorial of)
     }
    else
     {
       while (std::next_permutation(c.begin(), c.end()))
          if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend())
             ++count;
     }

    return count; // remember this return!
}

关于c++ - 常量迭代器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47337515/

相关文章:

java - 特定旅行商变体的实现

c++ - 以函数方式组合谓词

包含用户定义类型指针的 C++ vector

arrays - 无法将迭代器转换为 js_sys::Array

c++ - 没有规则使目标 '/usr/lib/x86_64-linux-gnu/libboost_filesystem.so`

c++ - 当您声明一个具有初始大小的数组时,它的元素最初是空字符串吗?

c++ - 如何有效地实现 std::tuple 使得空类型的元组本身就是空类型?

c++ - std::atomic_flag 不提供加载或存储操作有什么缺点吗? (自旋锁示例)

c++ - 将可变参数模板发送到结构时出现内部编译器错误 : Segmentation fault in gcc .

Rust 实现迭代器