Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) StdMax_elementExample1

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppStdMax_elementExample1/CppStdMax_elementExample1.pro

 

CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app

QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++

unix {
  QMAKE_CXXFLAGS += -Werror
}

SOURCES += main.cpp

win32 {
  INCLUDEPATH += \
    ../../Libraries/boost_1_54_0
}

 

 

 

 

 

./CppStdMax_elementExample1/main.cpp

 

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

struct MyClass
{
  MyClass(const std::string& s) : m_s{s} {}
  const std::string& Get() const noexcept { return m_s; }
  private:
  std::string m_s;
};

int main()
{
  std::vector<MyClass> v;
  v.push_back(MyClass("one"));
  v.push_back(MyClass("two"));
  v.push_back(MyClass("three"));
  v.push_back(MyClass("four"));
  v.push_back(MyClass("five"));
  v.push_back(MyClass("six"));

  //Find the shortest word and, if there multiple of the same length, the lexicographically first
  assert(
    std::min_element(v.begin(),v.end(),
      [](const MyClass& lhs, const MyClass& rhs)
      {
        if (lhs.Get().size() < rhs.Get().size()) return true;
        if (lhs.Get().size() > rhs.Get().size()) return false;
        return lhs.Get() < rhs.Get();
      }
    )->Get() == "one"
  );

  //Find the longest word and, if there multiple of the same length, the lexicographically last
  assert(
    std::max_element(v.begin(),v.end(),
      [](const MyClass& lhs, const MyClass& rhs)
      {
        if (lhs.Get().size() < rhs.Get().size()) return true;
        if (lhs.Get().size() > rhs.Get().size()) return false;
        return lhs.Get() < rhs.Get();
      }
    )->Get() == "three"
  );

  //Find the lexicographically first word
  assert(
    std::min_element(v.begin(),v.end(),
      [](const MyClass& lhs, const MyClass& rhs)
      {
        return lhs.Get() < rhs.Get();
      }
    )->Get() == "five"
  );

  //Find the lexicographically last word
  assert(
    std::max_element(v.begin(),v.end(),
      [](const MyClass& lhs, const MyClass& rhs)
      {
        return lhs.Get() < rhs.Get();
      }
    )->Get() == "two"
  );

}

 

 

 

 

 

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