简体   繁体   English

C ++如何找到向量中元素最后一次出现的位置

[英]C++ How to find position of last occurrence of element in vector

Let's say I have a vector with the numbers: 10 10 58 31 63 40 76 .假设我有一个带有数字的向量: 10 10 58 31 63 40 76 I want to find the position of the last occurrence of the minimum element.我想找到最小元素最后一次出现的位置。 The minimum element is 10 .最小元素是10 The position of the last occurrence of 10 is 1 .最后一次出现10的位置是1

I've tried using reverse iterators, but I'm still a little bit confused.我试过使用反向迭代器,但我还是有点困惑。

Assuming the vector:假设向量:

std::vector<int> v = { 10, 10, 58, 31, 63, 40, 76 };

You can get the last minimum element using reverse iterators and std::min_element :您可以使用反向迭代器和std::min_element获取最后一个最小元素:

auto last_min = std::min_element(std::rbegin(v), std::rend(v));

Then get the distance from the beginning of the vector using std::distance and the "base" of the reverse iterator :然后使用std::distance反向迭代器的“基数”获取与向量开头的距离:

auto last_min_distance = std::distance(std::begin(v), last_min.base());

Finally subtract one to get the index:最后减一得到索引:

auto last_min_index = last_min_distance - 1;

Your idea with the reverse iterator was the right thing to do.您使用反向迭代器的想法是正确的做法。 First you need to find the last element.首先,您需要找到最后一个元素。 This can be done with std::min_element and reverse iterators:这可以通过std::min_element和反向迭代器来完成:

auto min_elem_iter = std::min_element(std::crbegin(vec), std::crend(vec));

where vec is the std::vector you want to search through.其中vec是您要搜索的std::vector

Now you have an iterator to the last element you searched.现在您有了一个指向您搜索的最后一个元素的迭代器。 You need to check if it is the same as std::crend(vec) to make sure it points to a valid element.您需要检查它是否与std::crend(vec)相同,以确保它指向有效元素。

If you want to know the index, you need std::distance , which can be used to calculate the distance between two iterators.如果你想知道索引,你需要std::distance ,它可以用来计算两个迭代器之间的距离。 With that you can find out the distance between std::crbegin(vec) and the iterator which points to the element we found.有了它,您可以找出std::crbegin(vec)和指向我们找到的元素的迭代器之间的距离。 This can than be used together with the size of the vector to calculate the index.这可以与向量的大小一起使用来计算索引。

So all in all you can get what you want with:所以总而言之,你可以得到你想要的:

template<class T>
auto getIndexOfLastMin(const std::vector<T>& vec)
    -> std::optional<std::size_t>
{
    auto last_elem_iter = std::min_element(std::crbegin(vec), 
                                           std::crend(vec));
    if(last_elem_iter == std::crend(vec)){
        return std::nullopt;
    }
    
    auto idx = std::distance(std::rbegin(vec), last_elem_iter);
    return static_cast<std::size_t>(vec.size() -1 - idx);
}

You can checkout and run the code here您可以在此处签出并运行代码

let's say minimum element is k假设最小元素是 k

for (int i = 0; i < vector.size(); i++)
{
      if( k == vector[i])
      {
         index = i;
      }
}

At the end of the loop, index would be the last position of the minimum element in vector.在循环结束时,索引将是向量中最小元素的最后一个位置。

... And if you haven't found the minimum element up front, you can do: ...如果您没有预先找到最小元素,您可以这样做:

int min_element = std::numeric_limits <int>::max;
size_t index = 0;

for (size_t i = 0; i < vector.size(); i++)
{
    if (vector[i] <= min_element)
    {
        min_element = vector[i];
        index = i;
    }
}

Not everything has to be sophisticated (& this is the main pitfall of Modern C++: Any programmer tries to be a genius).并非一切都必须复杂(这是现代 C++ 的主要缺陷:任何程序员都想成为天才)。 Keep it simple:把事情简单化:

#include <vector>
#include <limits.h>

int main()
{
    std::vector<int> v = { 10, 10, 58, 31, 63, 40, 76 }; // This is the vector
    
    int min = INT_MAX;
    size_t i = 0, last_min_i = 0;

    for (auto item : v) {
        if (item <= min) {
            min = item;
            last_min_i  = i;
        }
        i++;
    }

    // last_min_i  holds the result
}

I'm assuming that you've already found the minimum element.我假设您已经找到了最小元素。 Then a simple backwards loop seems easiest然后一个简单的向后循环似乎最简单

size_t index = vec.size();
do
{
    --index;
}
while (vec.at(index) != min_element);

If by chance you've made a mistake then using at will result in an exception, that's a bit safer than the UB you'd get if you used [] .如果碰巧你犯了一个错误,那么使用at将导致异常,这比使用[]得到的 UB 更安全。

You could do something with reverse iterators but why complicate?你可以用反向迭代器做一些事情,但为什么复杂呢?

To find out the last occurrence of an element in a vector, we could use find_end().要找出向量中元素的最后一次出现,我们可以使用 find_end()。 It is used to find out the subsequence's last occurrence.它用于找出子序列的最后一次出现。

vector<int> v1 = {1,3,5,7,9};
vector<int> v2 = {7};
auto it = find_end(v1.begin(),v1.end(),v2,begin(),v2.end());

//printing the position of the element, use it-v1.begin();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM