Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用迭代器按谓词重新排列_C++_Algorithm_Sorting_Iterator - Fatal编程技术网

C++ 使用迭代器按谓词重新排列

C++ 使用迭代器按谓词重新排列,c++,algorithm,sorting,iterator,C++,Algorithm,Sorting,Iterator,在具有给定签名的函数中,我希望以这样的方式重新排列序列[first,last]的元素,即所有满足谓词的元素都放在不满足谓词的元素之前,并向不满足给定谓词的第一个元素返回迭代器 我的算法是 开始对序列进行迭代 如果当前元素不满足谓词,则用最后一个替换它 再次检查同一位置上的新元素是否满足要求 如果没有将其替换为(last-1),如果是,则继续 重复上述步骤,直到达到已更换的元件之一 我的代码 template<class Iterator, class Predicate> Ite

在具有给定签名的函数中,我希望以这样的方式重新排列序列[first,last]的元素,即所有满足谓词的元素都放在不满足谓词的元素之前,并向不满足给定谓词的第一个元素返回迭代器

我的算法是

  • 开始对序列进行迭代
  • 如果当前元素不满足谓词,则用最后一个替换它
  • 再次检查同一位置上的新元素是否满足要求
  • 如果没有将其替换为(last-1),如果是,则继续
  • 重复上述步骤,直到达到已更换的元件之一
我的代码

template<class Iterator, class Predicate>
Iterator Rearrange(Iterator first, Iterator last, Predicate pred) {
  auto res = first;
  if (first == last) {
    ;
  }
  else {
    auto run = first;
    auto end = last;
    auto tmp = *first;
    while (run != end) {
      if (pred(*run) == false) {
      again: tmp = *(--end);
    *end = *run;
    *run = tmp;
    if (pred(*run) == false) {
      goto again;
    }
      }
      ++run;
    }
  }
  return res;
}

我无法找到和理解。也就是说,我可以从某个地方读到我试图在容器外取消引用元素,但在我的程序中看不到它。有人能帮我修复编码错误或改进算法的逻辑吗?

如果输入范围为非空且其中没有元素满足谓词,则代码将被困在中ode>goto循环,并在再次时不到达
。最终,
--end
将在
第一次
之前执行
end

如果这是一个学习练习,我建议你摆脱
goto
;你不想学习坏习惯,虽然
goto
可以有罕见的合法用途,但替换循环不是其中之一。此外,与
tmp
跳舞可以用
std::swap
代替


如果这不是一个学习练习,就用它来做你想要的。< /P>我希望18年前,当工作从VB6移到C++时,然后C再也不需要处理<代码> Goto < /C>。
terminate called after throwing an instance of 'std::range_error'
  what():  dereferencing end of sequence
Aborted