Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) StdMinmax_elementExample2

 

C++11STLQt CreatorLubuntuWindows

 

std::minmax_element example 2 is an example of the std::minmax_element algorithm.

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppStdMinmax_elementExample2/CppStdMinmax_elementExample2.pro

 

include(../../ConsoleApplication.pri) #Or use the code below
# QT += core
# QT += gui
# greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
# CONFIG   += console
# CONFIG   -= app_bundle
# TEMPLATE = app
# CONFIG(release, debug|release) {
#   DEFINES += NDEBUG NTRACE_BILDERBIKKEL
# }
# QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++
# unix {
#   QMAKE_CXXFLAGS += -Werror
# }

SOURCES += main.cpp

 

 

 

 

 

./CppStdMinmax_elementExample2/main.cpp

 

#include <algorithm>
#include <cassert>
#include <map>

struct Id
{
  Id(const int id) : m_id(id) {}
  int m_id;
};

bool operator<(const Id& lhs, const Id& rhs) { return lhs.m_id < rhs.m_id; }

const std::pair<Id,Id> GetBestAndWorstIdStl(const std::map<Id,double>& m)
{
  const std::map<Id,double>::const_iterator end = m.end();
  std::map<Id,double>::const_iterator min = m.begin();
  std::map<Id,double>::const_iterator max = m.begin();
  for (std::map<Id,double>::const_iterator i = m.begin(); i!=end; ++i)
  {
    if (i->second < min->second) min = i;
    if (i->second >= max->second) max = i;
  }
  return std::make_pair(min->first,max->first);
}

const std::pair<Id,Id> GetBestAndWorstIdCpp11(const std::map<Id,double>& m)
{
  const auto p = std::minmax_element(m.begin(),m.end(),
    [](const std::pair<const Id,double>& lhs,const std::pair<const Id,double>& rhs)
    {
      return rhs.second > lhs.second;
    }
  );
  return std::make_pair((*p.first).first,(*p.second).first);
}

int main()
{
  const std::map<Id,double> m
    =
    {
      std::make_pair(Id(0), 0.0),
      std::make_pair(Id(1), 1.0),
      std::make_pair(Id(2), 0.0),
      std::make_pair(Id(3),-1.0),
      std::make_pair(Id(4), 0.0)
    };

  const auto p1 = GetBestAndWorstIdStl(m);
  assert(p1.first.m_id == 3);
  assert(p1.second.m_id == 1);

  const auto p2 = GetBestAndWorstIdCpp0x(m);
  assert(p2.first.m_id == 3);
  assert(p2.second.m_id == 1);

}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml