VOOZH about

URL: https://www.geeksforgeeks.org/cpp/utility-in-c/

⇱ <utility> in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

<utility> in C++

Last Updated : 25 Dec, 2023

It is a header file that contains utilities in unrelated domains. 

  • Pairs: These are the objects which can hold two different types of values. 
  • Generic Relational Approach: It is used for the relational operators !=, >, = under a specific namespace: rel_ops. 
  • Generic swap function: This a standard definition used by default by the components of the standard library for all types that do not provide their own overload: swap.

Functions: 

1. swap: It exchanges the value of two objects.


Output
a contains:10
20
30
40

2. make_pair: It constructs a pair with its first element set to x and its second element set to y.


Output
a: 10, 20
b: 15, B

3. move: It moves as rvalue. move is used to indicate that an object may be "moved from", i.e. allowing the transfer of resources from an object(to be moved) to another object.


Output
gfg contains: Hello!! I am a geek.

4. move (range of elements): It moves the elements in the range [first, last) into the range beginning at result. 
After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.


Output
Moving ranges...
string1 contains 5 elements
string2 contains 5 elements(after moving):Hello! I am a geek 

5. move_if_noexcept: It obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument.


Output
Non-throwing move constructor called
Throwing copy constructor called

6. decval: It returns an rvalue reference without referring to any object. 
This function selects the type of an argument as an rvalue reference if its move constructor never throw, or alternatively, as an lvalue reference if the type is copy-constructible. If the type is neither, the function returns an rvalue, which will be selected for move-only types (even if they may throw). 
Some operations can be implemented both by moving or by copying objects, generally moving for rvalues and copying for lvalues: Moving is generally a more efficient operation than copying when the object is no longer needed (such as rvalues).


Output
2000


Comment
Article Tags:
Article Tags: