【问题标题】:Why and when do we add pointer in front of the lowerbound function in c++?为什么以及何时在 C++ 中的下界函数前面添加指针?
【发布时间】:2020-08-17 00:53:15
【问题描述】:

所以,我在解决一个问题并编写了以下代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
   int t;
   cin >> t;

   while (t--)
   {
      int n, x;
      cin >> n;
      map <int, vector<int> > m;

      for (int i = 0; i < n; i++)
      {
         cin >> x;
         m[x].push_back(i);
      }
      int prev_ind = n;
      int ans = 0;

      for (auto i : m)
      {
         if (i.second.back() < prev_ind)
         {
            ans++;
            prev_ind = i.second[0];
         }
         else
            prev_ind = *lower_bound(i.second.begin(), i.second.end(), prev_ind);
      }
      cout << ans << endl;
   }
}

所以,当我从 lower_bound 函数的前面删除指针时,代码显示编译错误,谁能告诉我为什么会发生这种情况?

【问题讨论】:

  • lower_bound 前面添加* 并不是向任何东西“添加指针”。它取消引用函数返回的迭代器。 C++ 是一种上下文敏感的语言,各种符号在不同的上下文中表示不同的东西。 * 并不总是意味着“指针”。

标签: c++ c++11 iterator stdmap lower-bound


【解决方案1】:

你需要看看std::lower_bound

template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );
//^^^^^^^^ --> iterator

返回指向[first, last)范围内不小于(即大于或等于)值或last的第一个元素的迭代器如果没有找到这样的元素。

意思是,您将取消引用迭代器(即“来自std::lower_bound 前面的指针”,它被称为取消引用而不是指针)要获取下划线元素,并且如果您需要迭代器进行进一步操作,您将不会取消引用它。

在您的情况下,i.second 具有类型 std::vector&lt;int&gt; 并且正在做

std::lower_bound(i.second.begin(),i.second.end(), prev_ind);

根据条件返回指向元素的std::vector&lt;int&gt;::iterator。如果您需要访问该元素,则需要取消引用它。

std::vector<int>::iterator iter_prev_ind = std::lower_bound(i.second.begin(),i.second.end(), prev_ind);
prev_ind = *iter_prev_ind ;

简而言之,你写了什么

prev_ind = *std::lower_bound(i.second.begin(),i.second.end(),prev_ind);

但是,在取消引用 std::lower_bound 返回的迭代器之前,您应该小心,因为如果在 [first, last) 范围内没有找到这样的元素,它也可能是结束迭代器(学分@eeerorika)。

if(auto iter_prev_ind = std::lower_bound(i.second.begin(),i.second.end(),prev_ind);
   iter_prev_ind != i.second.end()) // if not iterator end
   prev_ind = *iter_prev_ind ;

另外,看看以下内容

【讨论】:

  • 请注意,一般来说,在通过指针间接访问之前,应该检查搜索是否找到了一个元素。
猜你喜欢
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 2013-09-12
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多