Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.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++ std::list的std::prev和std::next的有效性_C++_C++11_Iterator_Stdlist - Fatal编程技术网

C++ std::list的std::prev和std::next的有效性

C++ std::list的std::prev和std::next的有效性,c++,c++11,iterator,stdlist,C++,C++11,Iterator,Stdlist,我正在将迭代器存储到列表中: list<int> l; l.push_back(21); l.push_back(1); l.push_back(31); l.push_back(41); auto it = l.find(21); 如你所见,我需要确保所有的边界条件。如果出现以下情况,std::prev()和std::next()将返回哪些值: 它们是第一个和最后一个要素 或者如果它本身在某个点上变得无效 std::prev()和std::next()返回什么值 它们返回迭

我正在将迭代器存储到列表中:

list<int> l;
l.push_back(21); l.push_back(1); l.push_back(31); l.push_back(41);

auto it = l.find(21);
如你所见,我需要确保所有的边界条件。如果出现以下情况,
std::prev()
std::next()
将返回哪些值:

  • 它们是第一个和最后一个要素
  • 或者如果
    它本身在某个点上变得无效
std::prev()
std::next()
返回什么值

它们返回迭代器
it
n
th(其中
n
默认为1)前置或后继。参见此处了解/6和/7

。。。如果它们是第一个和最后一个元素;或者如果
它本身在某个点上变得无效

在调用之前,迭代器必须有效。如果
返回值是相应的边界迭代器之一,则返回值将是无效的迭代器;i、 e.
it==begin()
用于
prev(it)
it==end()
用于
next(it)

在将其用作
prev()
next()
的参数之前,需要确定
it
的有效性。并且没有理由确定迭代器的递减或递增是否会将迭代器置于容器的边界之外

因此,听起来您需要在算法的擦除部分为两个边界条件编写代码;第一个是
it==l.begin()
,第二个是
it==prev(l.end())
,如果找不到元素,可能还有第三个(因此
it==l.end()

auto prev = std::prev(it);
auto next = std::next(it);
*prev = *prev + *next;
l.erase(it);
// only proceed it something is found...
if (it != l.end()) {
  if (it == l.begin()) {
    // nothing to do...? element removed is the first one
  }
  else if (it == std::prev(l.end()) {
    // nothing? element removed is the last one....
  }
  else {
    auto prev = std::prev(it);
    auto next = std::next(it);
    *prev = *prev + *next;
  }
  l.erase(it); // remove the found element...
}