A function declared constexpr is
implicitly declared an inline function.
Wednesday, December 27, 2017
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.
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:
http://en.cppreference.com/w/cpp/numeric/math/copysign
http://en.cppreference.com/w/cpp/numeric/math/signbit
#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.
Reference: http://en.cppreference.com/w/cpp/error/errno
C++17(C11): Bounds-checking fopen_s() and freopen_s()
C++17 added the bounds-checking functions fopen_s() and freopen_s().
http://en.cppreference.com/w/c/io/fopen
http://en.cppreference.com/w/c/io/freopen
http://en.cppreference.com/w/c/io/fscanf
#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().
http://en.cppreference.com/w/c/algorithm/qsort
http://en.cppreference.com/w/c/algorithm/bsearch
#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().
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
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
time_t currentTime = 0;
struct tm currentTm;
char buffer[32];
localtime_s(¤tTm, ¤tTime);
asctime_s(buffer, sizeof(buffer), ¤tTm);
cout << buffer; // Wed Dec 31 19:00:00 1969
ctime_s(buffer, sizeof(buffer), ¤tTime);
cout << buffer; // Wed Dec 31 19:00:00 1969
gmtime_s(¤tTm, ¤tTime);
asctime_s(buffer, sizeof(buffer), ¤tTm);
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().
http://en.cppreference.com/w/c/string/byte/memcpy
http://en.cppreference.com/w/c/string/byte/memmove
#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().
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
#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:
https://stackoverflow.com/questions/38405260/difference-between-c99-and-c11
http://en.cppreference.com/w/c/io/gets
#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:
http://en.cppreference.com/w/cpp/utility/make_from_tuple
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0209r2.pdf
#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
Subscribe to:
Posts (Atom)