我正在尝试编写一个模板函数,它接受一个序列(通过 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/