Wednesday, December 27, 2017

C++11: Inline Function

A function declared constexpr is implicitly declared an inline function.



C++11: std::vector::shrink_to_fit()

C++11 added the vector function shrink_to_fit() to suggest to the system to reduce the capacity to size. Here is an example:

#include <iostream>
#include <vector>

int main()
{
  std::vector myVector;

  std::cout << myVector.capacity() << " "; // 15

  myVector.resize(1000);
  std::cout << myVector.capacity() << " "; // 1007

  myVector.clear();
  myVector.shrink_to_fit();
  std::cout << myVector.capacity() << " "; // 15

  std::cout << std::endl;
  return 0;
}
// Output: 0 1000 0
Reference: http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit

C++11: std::basic_string::shrink_to_fit()

C++11 added the string function shrink_to_fit() to suggest to the system to reduce the capacity to size. Here is an example:

#include <iostream>
#include <string>

int main()
{
  std::string myString;

  std::cout << myString.capacity() << " "; // 15

  myString.resize(1000);
  std::cout << myString.capacity() << " "; // 1007

  myString.clear();
  myString.shrink_to_fit();
  std::cout << myString.capacity() << " "; // 15

  std::cout << std::endl;
  return 0;
}
// Output: 15 1007 15
Reference: http://en.cppreference.com/w/cpp/string/basic_string/shrink_to_fit

C++98: std::istream_iterator

The istream_iterator template class wraps a stream and returns an input iterator. Here is an example:

#include <iostream>
#include <iterator>

int main()
{
  int myInt;
  std::istream_iterator<int> myIstreamIterator(std::cin);

  myInt = *myIstreamIterator;
  std::cout << myInt << " "; // 1

  myIstreamIterator++;
  myInt = *myIstreamIterator;
  std::cout << myInt << " "; // 2

  myIstreamIterator++;
  myInt = *myIstreamIterator;
  std::cout << myInt << " "; // 3

  std::cout << std::endl;  
  return 0;
}
// Input : 1 2 3
// Output: 1 2 3
Reference: http://www.cplusplus.com/reference/iterator/istream_iterator/

C++98: The boolalpha and nobool alpha Manipulators on cin

The boolalpha manipulator changes the way Boolean values are input from cin. Here is an example:

#include <iostream>

int main()
{
  bool dTrue   = false;
  bool dFalse  = false;
  bool szTrue  = false;
  bool szFalse = false;

  std::cin >> std::boolalpha;

  std::cin >> dTrue;
  std::cin >> dFalse;
  std::cin >> szTrue;
  std::cin >> szFalse;

  std::cout << dTrue   << " "; // 1
  std::cout << dFalse  << " "; // 0
  std::cout << szTrue  << " "; // 1
  std::cout << szFalse << " "; // 0

  std::cin >> std::noboolalpha;

  std::cin >> dTrue;
  std::cin >> dFalse;
  std::cin >> szTrue;
  std::cin >> szFalse;

  std::cout << dTrue   << " "; // 1
  std::cout << dFalse  << " "; // 0
  std::cout << szTrue  << " "; // 1
  std::cout << szFalse << " "; // 0

  std::cout << std::endl;
  return 0;
}
// Input : true false true false 1 0 1 0
// Output: 1 0 1 0 1 0 1 0
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 617.

C++98: The boolalpha and noboolalpha Manipulators on cout

The boolalpha manipulator changes the way Boolean values are output to cout. Here is an example:

#include <iostream>

int main()
{
  std::cout << true  << " "; // 1
  std::cout << false << " "; // 0

  std::cout << std::boolalpha;

  std::cout << true  << " "; // true
  std::cout << false << " "; // false

  std::cout << std::noboolalpha;

  std::cout << true  << " "; // 1
  std::cout << false << " "; // 0

  std::cout << std::endl;
  return 0;
}
// Output: 1 0 true false 1 0
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 617.

C++98: Standard Streams

There are eight C++ standard streams. The four narrow character streams are: cin, cout, cerr, and clog. The four wide-character streams are wcin, wcout, wcerr, and wclog.

Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 682.

C++98: User-Defined Manipulators

You can write your own stream manipulators. Here is an example:

#include <iostream>
#include <istream>

template <class charT, class traits>
inline std::basic_istream<charT, traits>&
printNextChar(std::basic_istream<charT, traits>& stream)
{
  char nextChar;

  nextChar = std::cin.get();
  std::cin.unget();

  std::cout << nextChar;

  return stream;
}


int main()
{
  char myChar;

  std::cin >> printNextChar;
  std::cin >> myChar;

  std::cout << myChar << std::endl;

  return 0;
}
// Input: A
// Output: AA
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 614.

C++98: cin.ignore()

The cin.ignore() function allows for a sequence of input characters to be ignored. Here is an example:

#include <iostream>

int main()
{
  int myInt1 = 0;
  int myInt2 = 0;

  std::cin >> myInt1; // 1

  std::cin.ignore(256, '\n'); // Extracts and discards characters

  std::cin >> myInt2; // 3

  std::cout << myInt1 << " "; // 1
  std::cout << myInt2 << " "; // 3

  std::cout << std::endl;

  return 0;
}
// Input: 
//   1 2
//   3 4
// Output:
//   1 3
Reference: http://www.cplusplus.com/reference/istream/istream/ignore/

C++98, 11, 14: Complex Numbers

The std::complex template class handles complex numbers. Here is an example:

// Euler's Identity: e**(i * pi) + 1 = 0
#include <complex>
#include <iostream>

const std::complex<double> I(0.0, 1.0);
const double               PI  = 3.141592653589793238463;

int main()
{
  std::complex<double> eRaisedToTheITimesPiPower;
  std::complex<double> lhs     ;
  std::complex<double> rhs     ;
  double               lhsAbs ;
  double               rhsAbs ;
  double               lhsArg ;
  double               rhsArg ;
  double               lhsReal;
  double               rhsReal;
  double               lhsImag;
  double               rhsImag;
  std::complex<double> lhs2    ;
  std::complex<double> rhs2    ;
  bool                 lhsIsEqualToRhs  ;
  bool                 lhs2IsEqualToRhs2;

  eRaisedToTheITimesPiPower = std::exp(I * PI);

  lhs     = eRaisedToTheITimesPiPower + 1.0;
  rhs     = std::complex<double>(0.0, 0.0);

  lhsAbs  = std::abs (lhs);
  rhsAbs  = std::abs (rhs);
  lhsArg  = std::arg (lhs);
  rhsArg  = std::arg (rhs);
  lhsReal = std::real(lhs);
  rhsReal = std::real(rhs);
  lhsImag = std::imag(lhs);
  rhsImag = std::imag(rhs);
  lhs2    = std::polar<double>(lhsReal, lhsImag);
  rhs2    = std::polar<double>(rhsReal, rhsImag);

  lhsIsEqualToRhs   = (lhs  == rhs );
  lhs2IsEqualToRhs2 = (lhs2 == rhs2);

  std::cout << eRaisedToTheITimesPiPower << " ";
  std::cout << lhs     << " ";
  std::cout << rhs     << " ";
  std::cout << lhsAbs  << " ";
  std::cout << rhsAbs  << " ";

  std::cout << std::endl;

  std::cout << lhsArg  << " ";
  std::cout << rhsArg  << " ";
  std::cout << lhsReal << " ";
  std::cout << rhsReal << " ";
  std::cout << lhsImag << " ";
  std::cout << rhsImag << " ";
  std::cout << lhs2    << " ";
  std::cout << rhs2    << " ";
  std::cout << lhsIsEqualToRhs  << " ";
  std::cout << lhs2IsEqualToRhs2 << " ";

  std::cout << std::endl;
  return 0;
}
// Output: (-1,1.22465e-16) (0,1.22465e-16) (0,0) 1.22465e-16 0
//         1.5708 0 0 0 1.22465e-16 0 (0,0) (0,0) 0 1
Reference: http://en.cppreference.com/w/cpp/numeric/complex

Tuesday, December 19, 2017

C++98: std::reverse()

std::reverse() reverses elements in a range. Strings have their own reverse() function. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>
#include <iterator>

int main()
{
  //            Index: 0  1  2  3  4  5  6  7
  int   sequence[8] = {1, 2, 3, 4, 5, 6, 7, 8};
  int * iter_beg    = &sequence[0];
  int * iter_end    = &sequence[8];

  std::reverse(iter_beg, iter_end);

  std::copy(&sequence[0]                             ,
            &sequence[8]                             ,
            std::ostream_iterator<int>(std::cout, " "));

  std::cout << std::endl;
  return 0;
}
// Output: 8 7 6 5 4 3 2 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 386-7.

C++98: std::swap_ranges()

std::swap_ranges() swaps elements of two ranges. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>
#include <iterator>

int main()
{
  //             Index: 0  1  2  3  4  5  6  7
  int   sequence1[8] = {1, 3, 3, 3, 1, 1, 1, 1};
  int   sequence2[8] = {1, 1, 1, 1, 4, 4, 4, 1};
  int * iter_beg1    = &sequence1[1]           ; // Point to    first 3.
  int * iter_end1    = &sequence1[4]           ; // Point after last  3.
  int * iter_beg2    = &sequence2[4]           ; // Point to    first 4.
  int * iter_end2    = NULL                    ;

  iter_end2 = std::swap_ranges(iter_beg1, // Points after original first 4.
                               iter_end1,
                               iter_beg2);
  std::copy(&sequence1[0]                             ,
            &sequence1[8]                             ,
            std::ostream_iterator(std::cout, " "));
  std::cout << ": ";
  std::copy(&sequence2[0]                             ,
            &sequence2[8]                             ,
            std::ostream_iterator(std::cout, " "));

  std::cout << std::endl;
  return 0;
}
// Output: 1 4 4 4 1 1 1 1 : 1 1 1 1 3 3 3 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 370-1.

C++98: std::lexicographical_compare()

std::lexicographical_compare() tests for ‘lexigraphically less than’ on two ranges. For strings, it is functionally equivalent to ‘<’. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>

int main()
{
  int sequence1[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence2[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence3[8] = {1, 3, 2, 4, 5, 7, 6};

  bool lhsIsLessThanRhs = false;

  lhsIsLessThanRhs = std::lexicographical_compare(&sequence1[0],
                                                  &sequence1[8],
                                                  &sequence2[0],
                                                  &sequence2[8]);

  std::cout << lhsIsLessThanRhs << " "; // 0

  lhsIsLessThanRhs = std::lexicographical_compare(&sequence2[0],
                                                  &sequence2[8],
                                                  &sequence3[0],
                                                  &sequence3[8]);

  std::cout << lhsIsLessThanRhs << " "; // 0

  lhsIsLessThanRhs = std::lexicographical_compare(&sequence3[0],
                                                  &sequence3[8],
                                                  &sequence1[0],
                                                  &sequence1[8]);

  std::cout << lhsIsLessThanRhs << " "; // 1


  std::cout << std::endl;
  return 0;
}
// Output: 0 0 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 360-2.

C++98: std::mismatch()

The template function std::mismatch() returns the pair of iterators where two sequences mismatch. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>

int main()
{
  int sequence1[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence2[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence3[8] = {1, 3, 2, 4, 5, 7, 6, 1};

  std::pair mismatchIterators;

  mismatchIterators = std::mismatch(&sequence1[0], 
                                    &sequence1[8],
                                    &sequence2[0]);  

  std::cout << mismatchIterators.first -&sequence1[0] << " "; // 8 (Index)
  std::cout << mismatchIterators.second-&sequence2[0] << " "; // 8 (Index)

  mismatchIterators = std::mismatch(&sequence1[0],
                                    &sequence1[8],
                                    &sequence3[0]);
  std::cout << *mismatchIterators.first  << " "; // 9 (Value)
  std::cout << *mismatchIterators.second << " "; // 1 (Value)

  std::cout << std::endl;
  return 0;
}
// Output: 8 8 9 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 158-60.

C++98: std::max_size()

You can query what the maxmum size of container is by using the template function std::max_size(). Here is an example:

#include <iostream>
#include <vector>

int main()
{
  std::vector<char     > Chars ;
  std::vector<short    > Shorts;
  std::vector<int      > Ints  ;
  std::vector<long long> Longs ;

  std::cout << Chars .max_size() << " ";
  std::cout << Shorts.max_size() << " ";
  std::cout << Ints  .max_size() << " ";
  std::cout << Longs .max_size() << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 2147483647 2147483647 1073741823 536870911
// Notes:
//   2147483647 (= 2.0 G - 1 = 31 bits)
//   1073741823 (= 1.0 G - 1 = 30 bits)
//   536870911  (= 0.5 G - 1 = 29 bits)
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 145.

C++98: std::Equal()

The template function std::Equal() compares two sequences. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>

int main()
{
  int sequence1[8] = {1, 3, 2, 4, 5, 7, 6, 8};
  int sequence2[8] = {1, 3, 2, 4, 5, 7, 6, 8};
  int sequence3[8] = {1, 3, 2, 4, 5, 7, 6, 1};

  std::cout << std::equal(&sequence1[0], &sequence1[8], &sequence2[0]) << " ";
  std::cout << std::equal(&sequence1[0], &sequence1[8], &sequence3[0]) << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 1 0
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 101.

C++98: Priority Queues

Priority Queues let items go to the head of the queue based on priority. Items with the same priority are not necessarily taken in order. Here is an example:

#include <iostream>
#include <queue>

enum Priority
{
  LOW,
  MEDIUM,
  HIGH
};

class Message
{
 public:
  Priority mPriority;
  int      mMessage;

  Message(int message)
  : mMessage(message), mPriority(MEDIUM)
  {}

  Message(int message, Priority priority)
  : mMessage(message), mPriority(priority)
  {}
};

struct PriorityLessThan
{
  bool operator()(Message lhs, Message rhs)
  {
    if ((int)lhs.mPriority < (int)rhs.mPriority)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
};

int main()
{
  std::priority_queue<Message             ,
                      std::vector<Message>,
                      PriorityLessThan    > priorityQueue;

  priorityQueue.push(Message(1        )); // 4th or 5th
  priorityQueue.push(Message(2, HIGH  )); // 1st or 2nd or 3rd 
  priorityQueue.push(Message(3, LOW   )); // 6th or 7th
  priorityQueue.push(Message(4, HIGH  )); // 1st or 2nd or 3rd 
  priorityQueue.push(Message(5, LOW   )); // 6th or 7th
  priorityQueue.push(Message(6, MEDIUM)); // 4th or 5th
  priorityQueue.push(Message(7, HIGH  )); // 1st or 2nd or 3rd 

  for (int i = 0; i < 7; i++)
  {
    std::cout << priorityQueue.top().mMessage << " ";
    priorityQueue.pop();
  }
  std::cout << std::endl;
  return 0;
}
// Output: 2 7 4 6 1 3 5
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 453-9.

C++98: std::inner_product()

The std::inner_product() template function computes the inner product of two sequences. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning
  // Alternatively, 
  //   Properties > Configuration Properties > C/C++ > Code Generation >
  //                Security Check > Disable Security Check(/GS-)

#include 
#include 

int main()
{
  int vector1[3]   = {1, 2, 3};
  int vector2[3]   = {4, 5, 6};
  int innerProduct = 0;

  innerProduct = std::inner_product(&vector1[0],&vector1[3],&vector2[0],0);

  std::cout << innerProduct << std::endl; // 32 = 1*4 + 2*5 + 3*6
  
  return 0;
}
// Output: 32
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 427-8.

C++11: std::fpclassify()

C++11 added the function std::classify(). It classifies a floating point number. Here is an example:

#include <cfloat>
#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  cout << fpclassify( 0.0       ) << " "; //  0 (=FP_ZERO     )
  cout << fpclassify(-0.0       ) << " "; //  0 (=FP_ZERO     )
  cout << fpclassify(-42.0      ) << " "; // -1 (=FP_NORMAL   )
  cout << fpclassify(DBL_MIN/2.0) << " "; // -2 (=FP_SUBNORMAL)
  cout << fpclassify(NAN        ) << " "; //  2 (=FP_NAN      )
  cout << fpclassify(INFINITY   ) << " "; //  1 (=FP_INFINITE )

  cout << ": ";

  cout << (0.0                 == -0.0               ) << " "; // 1
  cout << (DBL_MIN/2.0         == DBL_MIN            ) << " "; // 0
  cout << (DBL_MIN/2.0         == DBL_MIN/4.0        ) << " "; // 0
  cout << (DBL_MIN/DBL_MAX/2.0 == DBL_MIN/DBL_MAX/4.0) << " "; // 1

  cout << endl;
  return 0;
}
// Output: 0 0 -1 -2 2 1 : 1 0 0 1
Reference: http://en.cppreference.com/w/cpp/numeric/math/fpclassify

C++11: std::cbrt()

C++11 added the std::cbrt() function. It computes the cube root. Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  cout << cbrt(  1.0) << " "; //  1
  cout << cbrt(  8.0) << " "; //  2
  cout << cbrt( 27.0) << " "; //  3
  cout << cbrt( 64.0) << " "; //  4
  cout << cbrt(125.0) << " "; //  5 
  cout << cbrt(216.0) << " "; //  6 
  cout << cbrt(  2.0) << " "; //  1.25992
  cout << cbrt(  3.0) << " "; //  1.44225

  cout << endl;
  return 0;
}
// Output: 1 2 3 4 5 6 1.25992 1.44225
Reference: http://en.cppreference.com/w/cpp/numeric/math/cbrt

Monday, December 11, 2017

C++14: The Rule of Three/Five/Zero

Rule of Three – If a class requires either user-defined  destructor, copy constructor, or copy assignment, it usually requires all three.

Rule of Five – If Rule of Three is in action, and also move semantics are needed then the move constructor and move assignment operator are also needed.

Rule of Zero – “Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership.” – R. Martinho Fernandes

References:

C++14: std::exchange()

C++14 added the template function std::exchange(). Here is an example:

#include <utility>
#include <iostream>
using namespace std;

int main()
{
  int myObject   = 1;
  int myOldValue = 0.0;
  
  myOldValue = exchange(myObject, 9);

  cout << myOldValue << " " << myObject;

  cout << endl;
  return 0;
}
// Output: 1 9
Reference: http://en.cppreference.com/w/cpp/utility/exchange

C++11: std::rotate()

C++11 added the std::rotate function. Here is an example:

#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
  //                                0  1  2  3  4
  //                                -  -  -  -  -
  int   myArray[]                = {1, 2, 3, 4, 5};
  int * myArrayBeginIterator     = &myArray[0];
  int * myArrayMakeFirstIterator = &myArray[3];
  int * myArrayEndIterator       = &myArray[5];

  rotate(myArrayBeginIterator    ,
         myArrayMakeFirstIterator,
         myArrayEndIterator      );

  for (int * iter  = myArrayBeginIterator;
             iter != myArrayEndIterator  ;
           ++iter                         )
  {
    cout << *iter << " ";
  }

  cout << endl;
  return 0;
}
// Output: 4 5 1 2 3
Reference: http://en.cppreference.com/w/cpp/algorithm/rotate

C++11: std::nearbyint()

C++11 added the std::nearbyint() function. Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  cout << nearbyint(0.0) << " "; //  0
  cout << nearbyint(0.5) << " "; //  0
  cout << nearbyint(1.5) << " "; //  2
  cout << nearbyint(2.0) << " "; //  2
  cout << nearbyint(2.5) << " "; //  2

  cout << ": ";

  cout << nearbyint(-0.0) << " "; // -0
  cout << nearbyint(-0.5) << " "; // -0
  cout << nearbyint(-1.5) << " "; // -2
  cout << nearbyint(-2.0) << " "; // -2
  cout << nearbyint(-2.5) << " "; // -2

  cout << endl;
  return 0;
}
// Output: 0 0 2 2 2 : -0 -0 -2 -2 -2
Reference: http://en.cppreference.com/w/cpp/numeric/math/nearbyint

C++11: std::copysign() and std::signbit()

C++11 added the functions std::copysign() and std::signbit(). Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  cout << copysign(-11.0,  99.0) << " "; //  11
  cout << copysign(-11.0, -99.0) << " "; // -11
  cout << copysign( 11.0,  99.0) << " "; //  11
  cout << copysign( 11.0, -99.0) << " "; // -11

  cout << ": ";

  cout << signbit( 0.0) << " "; // 0
  cout << signbit(-0.0) << " "; // 1
  cout << signbit( 9.0) << " "; // 0
  cout << signbit(-9.0) << " "; // 1

  cout << endl;
  return 0;
}
// Output: 11 -11 11 -11 : 0 1 0 1
References:
http://en.cppreference.com/w/cpp/numeric/math/copysign
http://en.cppreference.com/w/cpp/numeric/math/signbit

C++11: std::remquo()

C++11 added the function std::remquo(). Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  int quo = 0.0;

  // C++11:    remainder = numerator - integerDividend * denominator
  // Notes:
  //  integerDividend = round(numerator/denominator) and is even when
  //    abs(integerDividend - numerator/denominator) = 1/2
  cout << remquo(1.0, 1.0, &quo) << ":" << quo << " "; //  0:0
  cout << remquo(1.0, 2.0, &quo) << ":" << quo << " "; //  1:1
  cout << remquo(1.0, 3.0, &quo) << ":" << quo << " "; //  1:0
  cout << remquo(1.0, 4.0, &quo) << ":" << quo << " "; //  1:0
  cout << remquo(2.0, 1.0, &quo) << ":" << quo << " "; //  0:0
  cout << remquo(3.0, 1.0, &quo) << ":" << quo << " "; //  0:2
  cout << remquo(4.0, 1.0, &quo) << ":" << quo << " "; //  0:3
  cout << ": ";

  cout << remquo(2.0, 2.0, &quo) << ":" << quo << " "; //  0:4
  cout << remquo(2.0, 3.0, &quo) << ":" << quo << " "; // -1:1
  cout << remquo(2.0, 4.0, &quo) << ":" << quo << " "; // -2:1
  cout << remquo(3.0, 2.0, &quo) << ":" << quo << " "; // -1:0
  cout << remquo(4.0, 2.0, &quo) << ":" << quo << " "; //  0:2
  cout << ": ";

  cout << remquo(3.0, 3.0, &quo) << ":" << quo << " "; //  0:2
  cout << remquo(3.0, 4.0, &quo) << ":" << quo << " "; // -1:1
  cout << remquo(4.0, 3.0, &quo) << ":" << quo << " "; //  1:1
  cout << ": ";

  cout << remquo(4.0, 4.0, &quo) << ":" << quo << " "; //  0:1

  cout << endl;
  return 0;
}
// Output:
//   0:0 1:1 1:0 1:0 0:0 0:2 0:3 : 0:4 -1:1 2:1 -1:0 0:2 : 0:2 -1:1 1:1 : 0:1
Reference: http://en.cppreference.com/w/cpp/numeric/math/remquo

C++11: std::remainder()

C++11 added the std::remainder() function. Here is an example:

#include <cmath>
#include <iostream>

int main()
{
  // C++11:    remainder = numerator - integerDividend * denominator
  // Notes:
  //  integerDividend = round(numerator/denominator) and is even when
  //    abs(integerDividend - numerator/denominator) = 1/2
  std::cout << std::remainder(1.0, 1.0) << " "; //  0 = 1 - round(1/1) * 1
  std::cout << std::remainder(1.0, 2.0) << " "; //  1 = 1 - round(1/2) * 2
  std::cout << std::remainder(1.0, 3.0) << " "; //  1 = 1 - round(1/3) * 3
  std::cout << std::remainder(1.0, 4.0) << " "; //  1 = 1 - round(1/4) * 4
  std::cout << std::remainder(2.0, 1.0) << " "; //  0 = 2 - round(2/1) * 1
  std::cout << std::remainder(3.0, 1.0) << " "; //  0 = 3 - round(3/1) * 1
  std::cout << std::remainder(4.0, 1.0) << " "; //  0 = 4 - round(4/1) * 1
  std::cout << ": ";

  std::cout << std::remainder(2.0, 2.0) << " "; //  0 = 2 - round(2/2) * 2
  std::cout << std::remainder(2.0, 3.0) << " "; // -1 = 2 - round(2/3) * 3
  std::cout << std::remainder(2.0, 4.0) << " "; // -2 = 2 - round(2/4) * 4
  std::cout << std::remainder(3.0, 2.0) << " "; // -1 = 3 - round(3/2) * 2
  std::cout << std::remainder(4.0, 2.0) << " "; //  0 = 4 - round(4/2) * 2
  std::cout << ": ";

  std::cout << std::remainder(3.0, 3.0) << " "; //  0 = 3 - round(3/3) * 3
  std::cout << std::remainder(3.0, 4.0) << " "; // -1 = 3 - round(3/4) * 4
  std::cout << std::remainder(4.0, 3.0) << " "; //  1 = 4 - round(4/3) * 3
  std::cout << ": ";

  std::cout << std::remainder(4.0, 4.0) << " "; //  0 = 4 - round(4/4) * 4
  std::cout << ": ";

  std::cout << std::remainder(3.0, 5.0) << " "; // -2 = 3 - round(3/5) * 5
  std::cout << std::remainder(5.0, 3.0) << " "; // -1 = 5 - round(5/3) * 3

  std::cout << std::remainder(-10.0, 3.0) << " ";//-1=10-round(-10/3)*3

  std::cout << std::endl;
  return 0;
}
// Output: 0 1 1 1 0 0 0 : 0 -1 2 -1 0 : 0 -1 1 : 0 : -2 -1 -1
Reference: http://www.cplusplus.com/reference/cmath/remainder/

C++11: std::fma()

C++11 added the std::fma() function. Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  double result      = 0.0;
  double lMuliplier  = 2.0;
  double rMultiplier = 3.0;
  double addendum    = 5.0;

  result = fma(lMuliplier, rMultiplier, addendum);//Fused Multiply Add

  cout << result << endl; // 11

  return 0;
}
// Output: 11
Reference: http://en.cppreference.com/w/cpp/numeric/math/fma

C++11: std::log2()

C++11 the function std::log2(), which takes the log base 2 of its input parameter. Here is an example:

#include <cfloat>
#include <iostream>
using namespace std;

int main()
{
  cout << log2(pow(2.0, 10.0)) << " "; // 10
  cout << log2(pow(2.0,  5.0)) << " "; //  5
  cout << log2(pow(2.0,  2.0)) << " "; //  2
  cout << log2(pow(2.0,  1.0)) << " "; //  1
  cout << log2(pow(2.0,  0.0)) << " "; //  0

  cout << ( log(pow(2.0, 10.0)) / log(2) ) << " "; // 10

  cout << endl;
  return 0;
}
// Output: 10 5 2 1 0 10
Reference: http://en.cppreference.com/w/cpp/numeric/math/log2

C++11: std::isinf()

C++11 added the function std::isinf() to test if a number is (+/-)infinite, and std::isfinite() to test the opposite. Here is an example:

#include <cfloat>
#include <iostream>
using namespace std;

int main()
{
  double one;
  double zero;

  one = 1.0;
  zero = 0.0;

  cout << std::isinf   (one /zero) << " "; // 1
  cout << std::isinf   (zero/one ) << " "; // 0

  cout << std::isfinite(one /zero) << " "; // 0
  cout << std::isfinite(zero/one ) << " "; // 1
 

  cout << endl;
  return 0;
}
// Output: 1 0 0 1

Reference: http://en.cppreference.com/w/cpp/numeric/math/isinf

Monday, December 4, 2017

C++11: errno went from static to thread-local

C++11 changed errno from a static to a thread-local variable.


C++17(C11): Bounds-checking fopen_s() and freopen_s()

C++17 added the bounds-checking functions fopen_s() and freopen_s().

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
  FILE    * fp1  ;
  FILE    * fp2  ;
  errno_t   errno;
  char      line[10];

  errno = fopen_s(&fp1, "test.txt", "w");
  cout << errno << " ";
  fprintf_s(fp1, "Hello");

  errno = freopen_s(&fp2, "test.txt", "r", fp1);
  cout << errno << " ";
  fscanf_s(fp2, "%s", line, sizeof(line));
  printf(line);

  cout << endl;
  return 0;
}
// Output: 0 0 Hello
References:
http://en.cppreference.com/w/c/io/fopen
http://en.cppreference.com/w/c/io/freopen
http://en.cppreference.com/w/c/io/fscanf

C++17(C11): Bounds-checking qsort_s() and bsearch_s()

C++17 added the bounds-checking functions qsort_s() and bsearch_s().

#include <cstdlib>
#include <iostream>
using namespace std;

// C++ standard has context as third parameter.
// MSVS 2017 has it as the first.
// int compareInt(const void * pLeft, const void * pRight, void * context)

int compareInt(void * context, const void * pLeft, const void * pRight)
{
  if (*(const int *)pLeft < *(const int *)pRight)
  {
    return -1;
  }
  else if (*(const int *)pLeft > *(const int *)pRight)
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

int main()
{
  int list[5] = {5, 4, 2, 3, 1};
  qsort_s(list, sizeof(list)/sizeof(int), sizeof(int), compareInt, NULL);
  for (int i : list)
  {
    cout << i << " ";
  }
 
  int key = 3;
  int * keyPointer = (int *)bsearch_s(&key                    ,
                                      list                    ,
                                      sizeof(list)/sizeof(int),
                                      sizeof(int)             ,
                                      compareInt              ,
                                      NULL                    );
  cout << ": " << (keyPointer - list);

  cout << endl;
  return 0;
}
// Output: 1 2 3 4 5 : 2
References:
http://en.cppreference.com/w/c/algorithm/qsort
http://en.cppreference.com/w/c/algorithm/bsearch

C++17(C11): Bounds-checking asctime_s(), ctime_s(), gmtime_s(), and localtime_s()

C++17 added the bounds-checking functions asctime_s(), ctime_s(), gmtime_s(), and localtime_s().

#include <ctime>
#include <iostream>
using namespace std;

int main()
{
  time_t    currentTime = 0;
  struct tm currentTm;
  char      buffer[32];

  localtime_s(&currentTm, &currentTime);
  asctime_s(buffer, sizeof(buffer), &currentTm);
  cout << buffer; // Wed Dec 31 19:00:00 1969

  ctime_s(buffer, sizeof(buffer), &currentTime);
  cout << buffer; // Wed Dec 31 19:00:00 1969

  gmtime_s(&currentTm, &currentTime);
  asctime_s(buffer, sizeof(buffer), &currentTm);
  cout << buffer; // Thu Jan  1 00:00:00 1970

  cout << endl;  
  return 0;
}
// Output: Wed Dec 31 19:00:00 1969
//         Wed Dec 31 19:00:00 1969
//         Thu Jan  1 00:00:00 1970
References:
http://en.cppreference.com/w/c/chrono/asctime
http://en.cppreference.com/w/c/chrono/ctime
http://en.cppreference.com/w/c/chrono/gmtime
http://en.cppreference.com/w/c/chrono/localtime

C++17(C11): Bounds-checking getenv_s()

C++17 added the bounds-checking function getenv_s().

#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
  char   buffer[20];
  size_t environmentVariableValueStringLength;

  getenv_s(&environmentVariableValueStringLength, buffer,
           sizeof(buffer) - 1, "OS");

  cout << buffer << endl;
  return 0;
}
// Output: Windows_NT
Reference: http://en.cppreference.com/w/c/program/getenv

C++17(C11)): Bounds-checking strerror_s() and strerrorlens()

C++17 added the bounds-checking functions strerror_s() and strerrorlens().

#include <iostream>
#include <cerrno>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
  // The following line does not compile on MSVS 2017:
  //   int bufferSize = strerrorlen_s(EINTR) + 1;
  const int bufferSize = FILENAME_MAX;
  char      buffer[bufferSize];

  strerror_s(buffer, bufferSize, EINTR);
  cout << buffer << endl;

  return 0;
}
// Output: Interrupted function call
Reference: http://en.cppreference.com/w/c/string/byte/strerror

C++17(C11)): Bounds-checking memcpy_s() and memmove_s()

C++17 added the bounds-checking functions memcpy_s() and memmove_s().

#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;

int main()
{
  char   jklmnop[ ] = "jklmnop";
  char   buffer1[7] = {0};
  char   buffer2[7] = {0};
 
  memcpy_s(buffer1, sizeof(buffer1), jklmnop,
           min(sizeof(buffer1), sizeof(jklmnop)));
  buffer1[6] = '\0';
  cout << buffer1 << " "; // jklmno

  memcpy_s(buffer2, sizeof(buffer2), jklmnop,
           min(sizeof(buffer1), sizeof(buffer2)));
  buffer2[6] = '\0';
  cout << buffer1 << " "; // jklmno
  cout << buffer2 << " "; // jklmno

  memmove_s(buffer2, sizeof(buffer2), jklmnop,
            min(sizeof(buffer1), sizeof(buffer2)));
  buffer2[6] = '\0';
  cout << buffer1 << " "; // jklmno
  cout << buffer2 << " "; // jklmno

  cout << endl;
  return 0;
}
// Output: jklmno jklmno jklmno jklmno jklmno
References:
http://en.cppreference.com/w/c/string/byte/memcpy
http://en.cppreference.com/w/c/string/byte/memmove

C++17(C11)): Bounds-checking strnlen_s(), strcpy_s, strncpy_s(), strcat_s() and strncat_s()

C++17 added the bounds-checking functions strnlen_s(),strcpy_s, strncpy_s(), strcat_s() and strncat_s().

#include <cstring>
#include <iostream>
using namespace std;

int main()
{
  char   abc    [ ] = "abc";
  char   def    [ ] = "def";
  char   ghi    [ ] = {'g', 'h', 'i'};
  char   jklmnop[ ] = "jklmnop";
  char   buffer [7] = {'A', 'A', 'A', 'A', 'A', 'A', 'A'};

  cout << sizeof(abc) << " " << sizeof(def) << " " << sizeof(ghi) << " : ";
  cout << strnlen_s(abc, sizeof(abc) - 1) << " " <<
          strnlen_s(def, sizeof(def) - 1) << " " <<
          strnlen_s(ghi, sizeof(ghi) - 1) << " ";

  strcpy_s(buffer, sizeof(buffer), abc);
  cout << buffer << " ";

  buffer[6] = 'A';
  strncpy_s(buffer, jklmnop, sizeof(buffer) - 1);
  cout << buffer << " ";

  buffer[6] = 'A';
  strcpy_s(buffer, sizeof(buffer), abc);
  strcat_s(buffer, sizeof(buffer), def);
  cout << buffer << " ";

  buffer[6] = 'A';
  strcpy_s(buffer, sizeof(buffer), abc); // Buffer needs a '\0' in it.
  strncat_s(buffer       ,
           sizeof(buffer), 
           jklmnop       ,
           sizeof(buffer) - strnlen_s(buffer, sizeof(buffer) - 1) - 1);
  cout << buffer << " ";

  cout << endl;
  return 0;
}
// Output: 4 4 3 : 3 3 2 abc jklmno abcdef abcjkl
References:
http://en.cppreference.com/w/c/string/byte/strlen
http://en.cppreference.com/w/c/string/byte/strcpy
http://en.cppreference.com/w/c/string/byte/strncpy
http://en.cppreference.com/w/c/string/byte/strcat
http://en.cppreference.com/w/c/string/byte/strncat

C++17(C11): The gets_s() Function

C++17(C11) removed the gets() function. The gets_s() function should be used instead. Here is an example:

#include <iostream>
#include <cstdio>
#include <cstdlib>


int main()
{
  char buffer[2] = {0, 0};

  try
  {
    gets_s(buffer, 2);
  }
  catch (...)
  {
  }
  std::cout << buffer << std::endl;

  return 0;
}
// Input : 5
// Output: 5
// Note: Any input longer that one character throws a program terminating 
//         exception on MSVS 2017.
References:
https://stackoverflow.com/questions/38405260/difference-between-c99-and-c11
http://en.cppreference.com/w/c/io/gets

C++17: std::make_from_tuple()

C++17 added the template function std::make_from_tuple() that allows you to construct an object from a tuple. Here is an example:

#include <iostream>
#include <tuple>

struct MyClass
{
  MyClass(int a, int b, int c)
  {
    std::cout << a << " " << b << " " << c << std::endl;
  }
};

int main()
{ 
  MyClass myObject = std::make_from_tuple<MyClass>(
                                       std::make_tuple(1, 2, 3));
  
  return 0;
}
// Output: 1 2 3
References:
http://en.cppreference.com/w/cpp/utility/make_from_tuple
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0209r2.pdf

Monday, November 27, 2017

C++11: Fixed Width Integer Macro Functions for Minimum Width Constants

C++11 added fixed width integer macro functions for minimum width constants. Here is an example:

#include <cstdint>
#include <iostream>
using namespace std;
 
int main()
{
  cout << sizeof(INT8_C   (42)) << " "; // 4
  cout << sizeof(INT16_C  (42)) << " "; // 4
  cout << sizeof(INT32_C  (42)) << " "; // 4
  cout << sizeof(INT64_C  (42)) << " "; // 8
  cout << sizeof(INTMAX_C (42)) << " "; // 8
  cout << sizeof(UINT8_C  (42)) << " "; // 4
  cout << sizeof(UINT16_C (42)) << " "; // 4
  cout << sizeof(UINT32_C (42)) << " "; // 4
  cout << sizeof(UINT64_C (42)) << " "; // 8
  cout << sizeof(UINTMAX_C(42)) << " "; // 8
 
  cout << endl;
  return 0;
}
// Output: 4 4 4 8 8 4 4 4 8 8
Reference: http://en.cppreference.com/w/cpp/types/integer

C++11: Fixed Width Integer Macro Constants

C++11 added fixed width integer macro constants. Here is an example:

#include <cstdint>
#include <iostream>
using namespace std;

int main()
{
  cout <<      INT8_MIN  << " "  ; // -128
  cout <<      INT16_MIN << " "  ; // -32768
  cout <<      INT32_MIN << " "  ; // -2147483648
  cout <<      INT64_MIN << "\n "; // -9223372036854775808
  cout << (int)INT8_MAX  << "  " ; // 127: Without cast, output was a symbol.
  cout <<      INT16_MAX << "  " ; // 32767
  cout <<      INT32_MAX << "  " ; // 2147483647
  cout <<      INT64_MAX << "  " ; // 9223372036854775807
  cout << endl;
  return 0;
}
// Output:
//    -128 -32768 -2147483648 -9223372036854775808
//     127  32767  2147483647  9223372036854775807
Reference: http://en.cppreference.com/w/cpp/types/integer

C++11: Fixed Width Integer Types

C++11 added fixed width integer types. Here is an example:

#include <cstdint>
#include <iostream>
using namespace std;

int main()
{
  cout << sizeof(int8_t       ) << " "; // 1
  cout << sizeof(int16_t      ) << " "; // 2
  cout << sizeof(int32_t      ) << " "; // 4
  cout << sizeof(int64_t      ) << " "; // 8
  cout << sizeof(int_fast8_t  ) << " "; // 1
  cout << sizeof(int_fast16_t ) << " "; // 4:fastest int at least 16 bits
  cout << sizeof(int_fast32_t ) << " "; // 4
  cout << sizeof(int_fast64_t ) << " "; // 8
  cout << sizeof(int_least8_t ) << " "; // 1
  cout << sizeof(int_least16_t) << " "; // 2:smallest int at least 16 bits
  cout << sizeof(int_least32_t) << " "; // 4
  cout << sizeof(int_least64_t) << " "; // 8
  cout << sizeof(intmax_t     ) << " "; // 8
  cout << endl;
  return 0;
}
// Output: 1 2 4 8 1 4 4 8 1 2 4 8 8
Reference: http://en.cppreference.com/w/cpp/types/integer

C++17: std::apply()

C++17 added the template function std::apply() to apply a function object to arguments from a tuple. Here is an example:


#include <iostream>
#include <tuple>

int main()
{
  std::apply([](int a, int b, int c)
             {
               std::cout << a << " " << b << " " << c << std::endl;
             },
             std::make_tuple(1, 2, 3));
  return 0;
}
// Output:: 1 2 3

Reference: http://en.cppreference.com/w/cpp/types/integer

C++11: std::tuple_cat()

C++11 added the template function std::tuple_cat() that concatenates all tuples passed to it into a single tuple. Here is an example:

#include <iostream>
#include <tuple>

int main()
{
  auto myTuple1   = std::make_tuple(1, 2);
  auto myTuple2   = std::make_tuple(3, 4);
  auto myTuple3   = std::make_tuple(5, 6);
  auto myTupleAll = std::tuple_cat(myTuple1, myTuple2, myTuple3);

  std::cout << std::get<0>(myTupleAll) << " "; // 1
  std::cout << std::get<1>(myTupleAll) << " "; // 2
  std::cout << std::get<2>(myTupleAll) << " "; // 3
  std::cout << std::get<3>(myTupleAll) << " "; // 4
  std::cout << std::get<4>(myTupleAll) << " "; // 5
  std::cout << std::get<5>(myTupleAll) << " "; // 6
  std::cout << std::endl;
  return 0;
}
// Output" 1 2 3 4 5 6
Reference: http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat

C++11: std::forward_as_tuple()

C++11 added the template function std::forward_as_tuple(), which creates a tuple that can be forwarded. If the arguments are rvalues, then the tuple members are rvalue references, otherwise the tuple members are lvalue members. Here is an example:

#include <iostream>
#include <map>
#include <string>
#include <tuple>

int main()
{
  std::map<std::string, std::string> myMap;

  myMap.emplace(
    std::piecewise_construct       ,  // pair CTOR selector
    std::forward_as_tuple("four_c"),  // pair first  CTOR args
                                      //  {string(string&& other)}
    std::forward_as_tuple(4, 'c'  )); // pair second CTOR args
                                      //  {string(size_type count,
                                      //   CharT ch)}
  std::cout << myMap["four_c"] << " ";

  // The '5' and 'c' are dangling references after the first semicolon.
  auto myTupleWithRvalueReferences = std::forward_as_tuple(5, 'c');

#if 0 // The following line does not compile, 
      //   because of the '5' and 'c' dangling references above.
  myMap.emplace(
    std::piecewise_construct       ,
    std::forward_as_tuple("five_c"),
    myTupleWithRvalueReferences    );
#endif

  std::cout << myMap["five_c"] << " ";

  int  count                       = 6  ;
  char ch                          = 'c';
  auto myTupleWithLvalueReferences = std::forward_as_tuple(count, ch);

  myMap.emplace(
    std::piecewise_construct      ,
    std::forward_as_tuple("six_c"),
    myTupleWithLvalueReferences   );

  std::cout << myMap["six_c"] << " ";

  std::cout << std::endl;
  return 0;
}
// Output: cccc  cccccc
Reference: http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple

C++11: std::tie() – tuple unpacking

The function template std::tie() allows you to unpack a tuple. Here is an example:

#include <iostream>
#include <tuple>

int main()
{
  int                                  a;
  double                               b;
  int                                  c;
  double                               d;
  std::tuple<int, double, int, double> myTuple{1, 2.2, 3, 4.4};

  std::tie(a, b, c, d) = myTuple;
  std::cout << a << " "; // 1
  std::cout << b << " "; // 2.0
  std::cout << c << " "; // 3
  std::cout << d << " "; // 4.0
  std::cout << std::endl;
  return 0;
}
// Output: 1 2.2 3 4.4
References: http://en.cppreference.com/w/cpp/utility/tuple

C++11: std::tie() – tuple packing

The function template std::tie() allows you to pack a tuple. Here is an example:

#include <iostream>
#include <tuple>

int main()
{
  int                                  a = 1  ;
  double                               b = 2.2;
  int                                  c = 3  ;
  double                               d = 4.4;
  std::tuple<int, double, int, double> myTuple;

  myTuple = std::tie(a, b, c, d);
  std::cout << std::get<0>(myTuple) << " "; // 1
  std::cout << std::get<1>(myTuple) << " "; // 2.0
  std::cout << std::get<2>(myTuple) << " "; // 3
  std::cout << std::get<3>(myTuple) << " "; // 4.0
  std::cout << std::endl;
  return 0;
}
// Output: 1 2.2 3 4.4
Reference: http://en.cppreference.com/w/cpp/utility/tuple

C++17: Function returning tuple initialization-list

C++17 allows a function to return an initialization-list for a tuple. Here is an example:

#include <iostream>
#include <tuple>

///////////////////////////////////////////////////////////////////////////////
std::tuple<int, double, int, double> returnTuple()
{
  return {1, 2.2, 3, 4.4};
}

int main()
{
  std::tuple<int, double, int, double> myTuple;

  myTuple = returnTuple();
  std::cout << std::get<0>(myTuple) << " "; // 1
  std::cout << std::get<1>(myTuple) << " "; // 2.0
  std::cout << std::get<2>(myTuple) << " "; // 3
  std::cout << std::get<3>(myTuple) << " "; // 4.0
  std::cout << std::endl;
  return 0;
}
// Output: 1 2.2 3 4.4
Reference: http://en.cppreference.com/w/cpp/utility/tuple

C++17: Structural Binding – Tuple Object

Below is an example of structurally binding a tuple object:

#include <iostream>
#include <tuple>

int main()
{
  std::tuple<int, double, int, double> myTuple{1, 2.2, 3, 4.4};

  auto [a, b, c, d] = myTuple;
  std::cout << a << " "; // 1
  std::cout << b << " "; // 2.0
  std::cout << c << " "; // 3
  std::cout << d << " "; // 4.0
  std::cout << std::endl;
  return 0;
}
// Output: 1 2.2 3 4.4
References:
http://en.cppreference.com/w/cpp/language/structured_binding
http://en.cppreference.com/w/cpp/utility/tuple

Tuesday, November 21, 2017

C++17: User-Defined Deduction Guides

User-defined deduction guides do not have to be templates.


C++17: Class Template Argument Deduction

Class template argument deduction is done only when no template parameters are given.


C++17: User-Defined Deduction Guides

User-defined deduction guides look like constructors with return types declared. They are of the following general form:

template<{TemplateParameters>ClassTemplateName(ConstructorParameters) ->
                                             ClassTemplateSpecialization;

Reference: http://en.cppreference.com/w/cpp/language/class_template_argument_deduction

C++17: Automatic Deduction Guides – Overloaded Fictional Template Function Selection

The return type of the selected fictional template function is used as the deduced class template specialization.


C++17: Fictional Template Functions

Fictional template functions return the class template type.



C++17: Automatic Deduction Guides

The automatic deduction guides are the set of fictional template functions generated by the compiler.


C++17: Automatic Deduction Guides - Fictional Template Functions

C++17 creates three kinds of fictional template functions to represent class template constructors: 1) those based on actually declared constructors; 2) one based on a hypothetical default constructor; and 3) one based on a hypothetical copy constructor.


C++17: Deduction Guides

C++17 can sometimes deduce class template parameters. To do this, C++17 uses Deduction Guides. There are two kinds of Deduction Guides: 1) Automatic Deduction Guides; and 2) User-Defined Deduction Guides.
References:

C++17: std::minmax_element()

C++17 added the algorithm std::minmax_element(), which returns iterators to both the first maximum value and the first minimum value over a range. Here is an example:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myVector{3, 1, 4, 1, 5, 9, 2, 6, 5};
  std::pair<std::vector<int>::iterator, std::vector<int>::iterator> minmax;

  minmax = std::minmax_element(myVector.begin(), myVector.end());

  std::cout << *minmax.first  << " "; // 1
  std::cout << *minmax.second << " "; // 9

  std::cout << std::endl;
  return 0;
}
// Output: 1 9
Reference: http://en.cppreference.com/w/cpp/algorithm/minmax_element

C++17: std::max_element() and std::min_element()

C++17 added the algorithms std::max_element() and std::min_element(), which return iterators to the first maximum or minimum value, respectively, over a range. Here is an example:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myVector{3, 1, 4, 1, 5, 9, 2, 6, 5};

  std::cout<<*(std::max_element(myVector.begin(),myVector.end()))<<" ";//9
  std::cout<<*(std::min_element(myVector.begin(),myVector.end()))<<" ";//1
  std::cout<<std::endl;
  return 0;
}
// Output: 9 1
References:
http://en.cppreference.com/w/cpp/algorithm/max_element
http://en.cppreference.com/w/cpp/algorithm/min_element

Monday, November 13, 2017

C++17: Class Template Argument Deduction

C++17 allows class template arguments to be deduced in certain cases. To be deduced, none of the class template arguments must be given.

C++17: std::destroy_at

C++17 added std::destroy_at() that can call the destructor of an object. Here is an example:

#include <memory>

int main()
{
  int * pInt = new int();

  *pInt = 1;

  std::destroy_at(pInt); // Destructor called, but 
                         //   memory is still allocated.

  *pInt = 2;

  delete pInt; // Destructor called, and memory is deallocated.

  // *pInt = 3; // Exception Thrown (in Debug Mode)

  return 0;
}
Reference: http://en.cppreference.com/w/cpp/memory/destroy_at

C++17: std::to_chars and std::from_chars

C++17 added std::to_chars to convert a value into a character string, and std::from_chars() to convert a character string into a value.

References:

C++17: std::visit

C++17 added the template function std::visit() that accepts a visitor, and variants; and applies the visitor to the variants.


C++17: std::search

C++17 extended std::search to use additional searching algorithms. The C++ library provides three algorithms, and the user may provide others.

References:


C++17: Node Handle

C++17 added node handles to associative containers that may be used for moves instead of copies. Here is an example:

#include <iostream>
#include <set>

int main()
{
  std::set<int> mySet{1, 2, 3};
  std::set<int> mySet2;

  std::set<int>::value_type myValue;
  //std::set<int>::node_type myNodeHandle = mySet.extract(2);
  //mySet2.insert(std::move(myNodeHandle));
  std::cout << mySet.count(1) << " ";
  std::cout << mySet.count(2) << " ";
  std::cout << mySet.count(3) << " ";

  std::cout << mySet2.count(1) << " ";
  std::cout << mySet2.count(2) << " ";
  std::cout << mySet2.count(3) << " ";

  return 0;
}
// Theoretical Output: 1 0 1 0 1 0
References:
http://en.cppreference.com/w/cpp/container/node_handle
https://stackoverflow.com/questions/39423059/when-do-i-use-node-type-with-stdmapinsert

C++17: std::launder

C++17 added the template function std::launder() to handle a corner case with placement new. Here is an example:

#include <iostream>
#include <new>

struct MyStruct
{
  const int mMyConst   ;
        int mMyVariable;
  MyStruct(int myConst, int myVariable)
  : mMyConst(myConst), mMyVariable(myVariable)
  {}
};

int main()
{
  MyStruct * pMyStruct = new MyStruct(1, 2);
  std::cout << pMyStruct->mMyConst    << " "; // Should be okay.
  std::cout << pMyStruct->mMyVariable << " "; // Should be okay.

  MyStruct * pMyStruct2 = new (pMyStruct) MyStruct(3, 4);//Using Placement New.
  std::cout << pMyStruct2->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct2->mMyVariable << " "; // Should be undefined.

  std::cout << pMyStruct->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct->mMyVariable << " "; // Should be undefined.

  new (pMyStruct) MyStruct(5, 6);
  std::cout << pMyStruct->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct->mMyVariable << " "; // Should be undefined.

  std::cout << pMyStruct2->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct2->mMyVariable << " "; // Should be undefined.

  //std::cout << std::launder(pMyStruct)->mMyConst    << " ";//Should be okay.
  //std::cout << std::launder(pMyStruct)->mMyVariable << " ";//Should be okay.

  std::cout << std::endl;
  return 0;
}
References:
http://en.cppreference.com/w/cpp/utility/launder
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0532r0.pdf

C++17: std::for_each_n

C++17 added the std::for_each_n() algorithm that takes an iterator, a count, and a function, and applies the function to the first ‘count’ elements starting at the ‘iterator’. Here is an example:

#include <algorithm>
#include <iostream>

int main()
{
  int myArray[]{1, 2, 3, 4, 5, 6, 7};

  std::for_each_n(&myArray[0], 4, [](auto & value) {value = value * value;});

  for (auto element : myArray)
  {
    std::cout << element << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 4 9 16 5 6 7
Reference: http://en.cppreference.com/w/cpp/algorithm/for_each_n

C++17: Execution Policy Types

C++17 has three execution policy types:

Class                                        Constant
-------------------------------------------  ---------
std::execution::sequenced_policy             std::execution::seq
std::execution::parallel_policy              std::execution::par
std::execution::parallel_unsequenced_policy  std::execution::par_unseq
  
These constants choose algorithm overloads with the corresponding policies.

"seq"       specifies that the algorithm must not be parallelized.
"par"       specifies that the algoritmm may      be parallelized.
"par_unseq" specifies that the algorithm may      be parallelized and
              in an unsequenced way.
References:
http://en.cppreference.com/w/cpp/algorithm/execution_policy_tag
http://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t

C++17: for (auto [key, value] : my_map) {…})

C++17 allows you to get key and values nicely in a ranged-base for loop. Here is an example:

#include <iostream>
#include <map>
#include <string>

int main()
{
  std::map<int, std::string> myMap{{1,"a"}, {2, "b"}, {3, "c"}};

  for (auto [key, value] : myMap)
  {
    std::cout << key << " " << value << " : ";
  }

  std::cout << std::endl;
  return 0;
}
// Output: 1 a : 2 b : 3 c :
Reference: https://www.infoq.com/news/2017/10/cpp-17-herb-sutter-interview

Monday, November 6, 2017

C++17: std::transform_inclusive_scan()

C++17 added std::transform_inclusive_scan(). This is the same as std::inclusive_scan(), except a unary function is first applied to each input item. Here is an example (simulated on C++14):

#include <iostream>
#include <vector>

namespace std17
{
  template<class InputIt        , class OutputIt      ,
           class BinaryOperation, class UnaryOperation>
  OutputIt transform_inclusive_scan(InputIt         first    ,
                                    InputIt         last     ,
                                    OutputIt        d_first  ,
                                    BinaryOperation binary_op,
                                    UnaryOperation  unary_op )
  {
    *d_first = unary_op(*first);
    first++;
    d_first++;
    for (auto iter = first; iter != last; iter++)
    {
      *d_first = binary_op(unary_op(*iter), *(d_first - 1));
      d_first++;
    }
    return d_first;
  }
}
int main()
{
  std::vector<int> myInputVector{1, 2, 3, 4, 5};
  std::vector<int> myOutputVector(5);

  std17::transform_inclusive_scan(myInputVector.begin(),
                                  myInputVector.end()  ,
                                  myOutputVector.begin(),
                                  [](auto a, auto b) {return a + b;},
                                  [](auto a) {return a * a;});
  for (auto item : myOutputVector) 
  {
    std::cout << item << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 5 14 30 55
Reference: http://en.cppreference.com/w/cpp/algorithm/transform_inclusive_scan

C++17: std::inclusive_scan()

C++17 added std::inclusive_scan(), which accepts a sequential input container and a sequential output container and iterates throught the input container while writing to the output container result of a binary operation on the previous result with the current input item. By default, the binary operation is addition, and the output container ends up with the integration of the input container. Here is an example (simulated with C++14):

#include <iostream>
#include <vector>

namespace std17
{
  template<class InputIt, class OutputIt>
  OutputIt inclusive_scan(InputIt first, InputIt last, OutputIt d_first)
  {
    *d_first = *first;
    first++;
    d_first++;
    for (auto iter = first; iter != last; iter++)
    {
      *d_first = *iter + *(d_first - 1);
      d_first++;
    }
    return d_first;
  }
}

int main()
{
  std::vector<int> myInputVector{1, 2, 3, 4, 5};
  std::vector<int> myOutputVector(5);

  std17::inclusive_scan(myInputVector.begin() ,
                        myInputVector.end()   ,
                        myOutputVector.begin());
  for (auto item : myOutputVector) 
  {
    std::cout << item << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 3 6 10 15
References:
http://en.cppreference.com/w/cpp/algorithm/inclusive_scan
http://www.modernescpp.com/index.php/c-17-new-algorithm-of-the-standard-template-library

C++17: std::transform_reduce()

C++17 added std:: transform_reduce, which applies a functor, then reduces. The default functor is multiplication. Here is an example (simulated with C++14):

#include <iostream>
#include <vector>
 
namespace std17
{
  template<class InputIt, class T, class BinaryOp, class UnaryOp>
  T transform_reduce(InputIt  first   ,
                     InputIt  last    ,
                     T        init    ,
                     BinaryOp binop   ,
                     UnaryOp  unary_op)
  {
    T generalizedSum = init;
    for (auto iter = first; iter != last; iter++)
    {
      generalizedSum = binop(unary_op(*iter), generalizedSum);
    }
    return generalizedSum;
  }
}
 
int main()
{
  std::vector<int> myInputVector{1, 2, 3, 4, 5};
  int              result;
 
  result = std17::transform_reduce(myInputVector.begin(),
                                   myInputVector.end()  ,
                                   0                    ,
                                  [](auto a, auto b) {return a + b;},
                                  [](auto a        ) {return a * a;});
  std::cout << result << std::endl;
  return 0;
}
// Output: 55
Reference: http://en.cppreference.com/w/cpp/algorithm/transform_reduce

C++17: std::reduce()

C++17 added std::reduce(), which applies applies a binary operation on a range of elements. The default binary operation is addition. Here is an example (simulated with C++14):

#include <iostream>
#include <vector>

namespace std17
{
  template<class InputIt>
  typename std::iterator_traits<InputIt>::value_type
  reduce(InputIt first, InputIt last)
  {
    std::iterator_traits<InputIt>::value_type sum =
                 std::iterator_traits<InputIt>::value_type();
    for (auto iter = first; iter != last; iter++)
    {
      sum = sum + *iter;
    }
    return sum;
  }
}

int main()
{
  std::vector<int> myInputVector{1, 2, 3, 4, 5};
  int              result;

  result = std17::reduce(myInputVector.begin() ,
                         myInputVector.end()   );

  std::cout << result << " ";
  std::cout << std::endl;
  return 0;
}
// Output: 15
Reference: http://en.cppreference.com/w/cpp/algorithm/reduce

C++17: New Headers

C++17 added the following headers:

<any>
<execution>
<memory_resource>
<optional>
<string_view>
<variant>
Reference: http://en.cppreference.com/w/cpp/header

C++: SFINAE

SFINAE stands for “Substitution Failure is Not an Error”. When deducing which template function to use, if the compiler tries one template function, and if the substitution of template parameters is a problem; instead of the compiler declaring an error and stopping, the compiler tries the remaining template functions.

References:

C++17: std::gcd() and std::lcm()

C++17 added the greatest common divisor (GCD) function and the least common multiple (LCM) function.

#include 
#include 

int main()
{
  std::cout << std::gcd( 0, 10) << " "; // 10 
  std::cout << std::gcd( 1, 10) << " "; //  1
  std::cout << std::gcd( 2, 10) << " "; //  2
  std::cout << std::gcd( 3, 10) << " "; //  1
  std::cout << std::gcd( 4, 10) << " "; //  2
  std::cout << std::gcd( 5, 10) << " "; //  5
  std::cout << std::gcd( 6, 10) << " "; //  2
  std::cout << std::gcd( 7, 10) << " "; //  1
  std::cout << std::gcd( 8, 10) << " "; //  2
  std::cout << std::gcd( 9, 10) << " "; //  1
  std::cout << std::gcd(10, 10) << " "; // 10

  std::cout << ": ";

  std::cout << std::lcm( 0, 10) << " "; //  0 
  std::cout << std::lcm( 1, 10) << " "; // 10
  std::cout << std::lcm( 2, 10) << " "; // 10
  std::cout << std::lcm( 3, 10) << " "; // 30
  std::cout << std::lcm( 4, 10) << " "; // 20
  std::cout << std::lcm( 5, 10) << " "; // 10
  std::cout << std::lcm( 6, 10) << " "; // 30
  std::cout << std::lcm( 7, 10) << " "; // 70
  std::cout << std::lcm( 8, 10) << " "; // 40
  std::cout << std::lcm( 9, 10) << " "; // 90
  std::cout << std::lcm(10, 10) << " "; // 10

  std::cout << std::endl;
  return 0;
}
// Output: 10 1 2 1 2 5 2 1 2 1 10 : 0 10 10 30 20 10 30 70 40 90 10
References:
http://en.cppreference.com/w/cpp/numeric/gcd
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0295r0.pdf

C++17: C++17 is based on C11 instead of C99.

C++17 is based on C11 instead of C99.


C++17: std::clamp()

C++17 added the template function std::clamp() is a combination of std::max() and std::min(). Here is an example:

#include <algorithm>
#include <iostream>

int main()
{
  //                      Value Min Max
  std::cout << std::clamp( 5   ,  0, 10) << " "; //  5
  std::cout << std::clamp(-5   ,  0, 10) << " "; //  0
  std::cout << std::clamp(20   ,  0, 10) << " "; // 10

  std::cout << std::endl;
  return 0;
}
// Output: 5 0 10
Reference: https://stackoverflow.com/questions/38060436/what-are-the-new-features-in-c17

C++17: The register keyword was removed.

C++17 removed the register keyword. This keyword used to be used to hint to the compiler that a local variable is used so much that it would be nice to use a CPU Register for it instead of the stack.

Monday, October 30, 2017

C++17: std::invoke

C++17 added the std::invoke() function, which takes a callable object and parameters; and calls the callable object with the parameters.

References:


C++17: operator++(bool) was removed

C++17 removed the operator++(bool) function.


C++17: Logical operator traits

C++17 added the type traits: conjunction, disjunction, and negation.

References:


C++17: std::byte

C++17 added the std::byte type, which is neither a character nor a mathematical object.  It represents only a collection of bits.

References:


C++17: tagged union container

C++17 added a tagged union container. It is called std::variant. Here is an example:

#include <iostream>
#include <variant>

int main()
{
  std::variant<short, int, std::string> myVariant;

  myVariant = (short)1;

  std::cout << std::get<short>(myVariant) << " ";
  std::cout << std::get<0    >(myVariant) << " ";

  myVariant = 2;
  std::cout << std::get<int>(myVariant) << " ";
  std::cout << std::get<1  >(myVariant) << " ";

  myVariant = std::string("Three");
  std::cout << (std::get<std::string>(myVariant)).c_str() << " ";
  std::cout << (std::get<2          >(myVariant)).c_str() << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 1 1 2 2 Three Three
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/utility/variant

C++17: Bessel functions

C++17 added the following Bessel functions:

regular modified cylindrical Bessel functions 
cyl_bessel_i
cyl_bessel_if
cyl_bessel_il

cylindrical Bessel functions (of the first kind)  
cyl_bessel_j
cyl_bessel_jf
cyl_bessel_jl
  
irregular modified cylindrical Bessel functions 
cyl_bessel_k
cyl_bessel_kf
cyl_bessel_kl
  
spherical Bessel functions (of the first kind) 
sph_bessel
sph_besself
sph_bessell
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/numeric/special_math

C++17: elliptic integrals

C++17 added the following elliptic integral functions:

(complete) elliptic integral of the first kind 
comp_ellint_1
comp_ellint_1f
comp_ellint_1l
 
(complete) elliptic integral of the second kind 
comp_ellint_2
comp_ellint_2f
comp_ellint_2l
  
(complete) elliptic integral of the third kind 
comp_ellint_3
comp_ellint_3f
comp_ellint_3l
  
(incomplete) elliptic integral of the first kind 
ellint_1
ellint_1f
ellint_1l
  
(incomplete) elliptic integral of the second kind 
ellint_2
ellint_2f
ellint_2l
  
(incomplete) elliptic integral of the third kind 
ellint_3
ellint_3f
ellint_3l
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/numeric/special_math
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1422.html

C++17: Parallel versions of STL algorithms

C++17 added parallel versions of some STL algorithms. Here is an example:

// The following program neither compiles on MSVS 2017 nor gcc version 6.3.0.
#include <algorithm>
//#include <execution>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myVector{3, 1, 4, 5, 9, 2, 6};
//std::sort(std::execution::par, myVector.begin(), myVector.end());
  for (auto i : myVector)
  {
    std::cout << i << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Theoretical Output: 1 2 3 4 5 6 9
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://www.bfilipek.com/2017/01/cpp17features.html#merged-the-parallelism-ts-aka-parallel-stl
http://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t
http://en.cppreference.com/w/cpp/algorithm/sort

C++17: New file system library

C++17 added a file system library. Here is an example:

#include <filesystem>
#include <iostream>

// "experimental" and "v1" are needed for MSVS 2017.
namespace fs = std::experimental::filesystem::v1;

int main()
{
  fs::path myPath (".\\cpp17filesystem.cpp");
  fs::path myPath2(".\\junk.txt"           );
  bool     fileWasRemoved                   = false;

  std::cout << fs::exists(myPath)  << " "; // 1
  std::cout << myPath.stem()       << " "; // cpp17filesystem
  std::cout << myPath.extension()  << " "; // .cpp
  fs::remove(myPath2);
  std::cout << fs::exists(myPath2) << " "; // 0
  fs::copy(myPath, myPath2);
  std::cout << fs::exists(myPath2) << " "; // 1
  fileWasRemoved = fs::remove(myPath2);
  std::cout << fileWasRemoved      << " "; // 1
  fileWasRemoved = fs::remove(myPath2);
  std::cout << fileWasRemoved      << " "; // 0
  std::cout << std::endl;
  return 0;
}
// Output: 1 cpp17filesystem .cpp 0 1 1 0
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/filesystem
http://www.bfilipek.com/2017/01/cpp17features.html#merged-file-system-ts
http://www.bfilipek.com/2017/08/cpp17-details-filesystem.html

C++17: Old Function Adapters Removed

C++17 removed the following binder and adaptor functions.

unary_function
binary_function
binder1st
binder2nd
bind1st
bind2nd
pointer_to_unary_function
pointer_to_binary_function
ptr_fun
mem_fun_t
mem_fun1_t
const_mem_fun_t
const_mem_fun1_t
mem_fun
mem_fun_ref_t
mem_fun1_ref_t
const_mem_fun_ref_t
const_mem_fun1_ref_t
mem_fun_ref
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/utility/functional