【问题标题】:Why i am not able to find index of an element in the vector? [duplicate]为什么我无法在向量中找到元素的索引? [复制]
【发布时间】:2015-08-01 06:38:19
【问题描述】:

我得到了正确的max 元素,但不是最大元素的索引。元素的索引等于max 元素。

long int maxi=*max_element(segments.begin(),segments.end());

long int index=*find(segments.begin(),segments.end(),maxi);

【问题讨论】:

  • 是的,因为它最大的元素。阅读find()的文档。
  • 我投票决定将此问题作为离题结束,因为通过阅读文档可以轻松回答。

标签: c++


【解决方案1】:

试试这个:

long int index=find(segments.begin(),segments.end(),maxi) - segments.begin();

Find 返回一个 iterator 到最大元素,对于向量,它的行为主要类似于指针。你正在做的是取消引用它(它只是让你得到它指向的东西,最大元素)。相反,计算该迭代器与起始迭代器之间的距离以获取索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 2017-04-15
    • 1970-01-01
    • 2018-04-11
    • 2017-11-07
    • 2018-08-04
    • 2011-10-23
    • 2020-11-02
    相关资源
    最近更新 更多