在向量C ++中查找多个max元素

时间:2020-04-21 18:02:57

标签: c++ vector max

所以..我正在尝试查找向量的最大值及其在向量中的位置。我正在使用for循环,并且工作正常。我的问题是,如果最大值出现多次,那么我想知道矢量中出现最大值的所有位置。那么,我该如何处理呢? 到目前为止,这是我正在使用的代码:(称为v的向量具有我从文件中读取的元素,但我不会添加代码的那一部分)

std::vector<double>v;
double maxvalue;
int position=0;
maxvalue = v[0];

for (unsigned int i=0; i<v.size(); i++){
    if (v[i]> maxvalue){
        maxvalue=v[i];
        position= i;
    }
}

4 个答案:

答案 0 :(得分:3)

您可以修改方法,以保留出现最大值的索引向量

#include <cfloat>
#include <iostream>
#include <utility>
#include <vector>

std::pair<double, std::vector<std::size_t>> FindMaxElements(std::vector<double> const& v)
{
    std::vector<std::size_t> indices;
    double current_max = -DBL_MAX;

    for (std::size_t i = 0; i < v.size(); ++i)
    {
        if (v[i] > current_max)
        {
            current_max = v[i];
            indices.clear();
        }

        if (v[i] == current_max)
        {
            indices.push_back(i);
        }
    }

    return std::make_pair(current_max, indices);
}

int main()
{
    auto result = FindMaxElements({1, 4, 7, 2, 7, 3});
    std::cout << "max: " << result.first << '\n';
    std::cout << "indices: ";
    for (auto i : result.second)
         std::cout << i << ' ';
}

输出

max: 7
indices: 2 4  

答案 1 :(得分:2)

这是使用标准库的两遍版本(而没有它,可能会更干净):

#include <vector>
#include <algorithm>

int main()
{
    std::vector<double> v {/* fill it*/ };
    std::vector<int> pos;

    auto it = std::max_element(std::begin(v), std::end(v));
    while (it != std::end(v))
    {
        pos.push_back(std::distance(std::begin(v), it));
        it = std::find(std::next(it), std::end(v), *it);
    }
    //...
}

答案 2 :(得分:1)

下面的函数模板find_maximums()返回一个std::vector<size_t>,其中包含输入向量中最大值的位置。请注意,如果输入向量为空,它将返回索引的空向量。

template<typename T>
auto find_maximums(const std::vector<T>& v) {
   std::vector<size_t> indexes;

   for (auto it_max = std::max_element(v.begin(), v.end()); it_max != v.end();
        it_max = std::find(it_max+1, v.end(), *it_max))
   {
      auto index = std::distance(v.begin(), it_max);
      indexes.push_back(index);
   }

   return indexes;
}

作为使用示例:

auto main() -> int {
   std::vector<int> v = {11, 7, 3, 11, 0, 7, 1, 11, 11};
   auto max_indexes = find_maximums(v);

   if (max_indexes.empty())
      return 1;

   std::cout << "max: " << v[max_indexes.front()] << std::endl;
   std::cout << "max at positions: ";
   for (auto idx: max_indexes)
      std::cout << idx << ' ';
   std::cout << '\n';
}

它输出:

max: 11
max at positions: 0 3 7 8

答案 3 :(得分:0)

我的两分钱,传递了几个迭代器和一个比较器

template <class It,
          class Comp = std::less<typename std::iterator_traits<It>::value_type>>
auto max_elements_indices(It first, It last, Comp cmp = Comp{})
{
    // This function returns a vector of indices, so to get the maximum, the caller
    // should first check if the returned vector is empty and then use one of
    // those indices to retrieve the value.
    std::vector<std::size_t> indices;
    if (first == last)
        return indices;

    // Using the first element instead of a sentinel value is easier to generalize
    indices.push_back(0);
    auto value = *first;

    for (auto i = std::next(first); i != last; ++i)
    {
        // The most common case should be an element below the maximum
        if ( cmp(*i, value) )
            continue;
        else
        {
            if ( cmp(value, *i) )
            {
                value = *i;
                indices.clear();
            }
            indices.push_back(std::distance(first, i));
        }
    }
    return indices;
}

可测试的here