【问题标题】:What is the best way to find the position of the last occurrence for a specific item? [duplicate]查找特定项目最后一次出现位置的最佳方法是什么? [复制]
【发布时间】:2015-05-16 18:25:09
【问题描述】:

类似但相反的东西:

int pos = find(v.begin(), v.end(), item) - v.begin();

【问题讨论】:

  • 什么是容器?
  • 容器是一个 std::vector

标签: c++ c++11 c++14


【解决方案1】:

您可以使用std::find,但使用容器提供的反向迭代器:

auto it = std::find(v.rbegin(), v.rend(), item);
int index = v.rend() - it + 1;

您需要+1,因为v.rend()“指向”元素-1,即“过去”第一个元素。

【讨论】:

  • 谢谢!这正是我正在寻找的:)
【解决方案2】:

使用reverse iterators:

find(v.rbegin(), v.rend(), item);

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 1970-01-01
    • 2012-04-14
    • 2017-04-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多