Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C++ Programming Code Examples

C++ > Code Snippets Code Examples

Remove copy Elements if They Meet a Criterion

/* Remove copy Elements if They Meet a Criterion */ #include <algorithm> #include <functional> #include <vector> #include <iostream> using namespace std; template <class T> void print(T& c){ for( typename T::iterator i = c.begin(); i != c.end(); i++ ){ std::cout << *i << endl; } } template<class InputIterator, class OutputIterator, class Predicate > OutputIterator copy_if( InputIterator start, InputIterator stop,OutputIterator out, Predicate select ){ while( start != stop ){ if( select( *start ) ) *out++ = *start; ++start; } return out; } int main( ) { const int numbers = 7; const int num[numbers] = { -5, 0, 13, 20, 10, 4, -1 }; vector<int> v1( num, num+numbers ); print( v1 ); vector<int> v2( num, num+numbers ); vector<int>::const_iterator v2_copy_end = remove_copy_if( v1.begin(), v1.end(), v2.begin(),not1( bind2nd( greater<int>(), 10 ) ) ); for( vector<int>::const_iterator i = v2.begin(); i != v2_copy_end;++i ) cout << *i << " "; }

A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration.

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

Return function object with second parameter bound. This function constructs an unary function object from the binary function object op by binding its second parameter to the fixed value x. The function object returned by bind2nd has its operator() defined such that it takes only one argument. This argument is used to call binary function object op with x as the fixed value for the second argument. This function template creates a binder2nd function object. The bind2nd function is a convenient way to construct a binder2nd object. Use bind2nd when you have a binary function and always want to supply the same value as the first argument to the function.

Copy certain elements of range. C++ Algorithm copy_if() function is used to copy the elements of the container [first,last] into a different container starting from result for which the value of pred is true. Copies the elements in the range [first,last) for which pred returns true to the range beginning at result. copy_if() function is a library function of algorithm header, it is used to copy the elements of a container, it copies the certain elements (which satisfy the given condition) of a container from the given start position to another container from the given beginning position.

Return iterator to end. Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as vector::begin. This function does not accept any parameter.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

Function object class for greater-than inequality comparison. Binary function object class whose call returns whether the its first argument compares greater than the second (as returned by operator >). The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function. This can also be used with various standard algorithms such as sort, priority queue, etc. Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call.

Return negation of unary function object. Constructs a unary function object (of a unary_negate type) that returns the opposite of pred (as returned by operator !). This function takes unary function object and returns its complement object. Here we need to define argument_type for unary functor in our functor.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Copy range removing values. Copies the elements in the range [first,last) to the range beginning at result, except those elements for which pred returns true. The resulting range is shorter than [first,last) by as many elements as matches, which are "removed". C++ Algorithm remove_copy_if() function is used to copy all elements in the range [first, last) to the range beginning at result, except those elements for which pred returns true without disturbing the order of the remaining elements. The function shall not modify its argument. This can either be a function pointer or a function object. The ranges shall not overlap.

Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration. T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T.

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program. The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index.

Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector. This function does not accept any parameter.

Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result. • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used.