Python Program to Set nth Bit of a Number

Program to Set nth Bit of a Number

In the previous article, we have discussed Python Program to Get nth Bit of a Number

Given a number and the bit position, the task is to set the nth bit of the given Number.

For example:

Let the number = 5

Bit position=1

To set the 1st-bit position(0 indexing):

Its binary form = 101

When we set the 0 at the 1st index becomes 1 that is 111 which is equal to the number 7.

Bitwise or (|) operator:

If one of two bits is 1, sets each bit to 1.

Examples:

Example1:

Input:

Given Number = 5 
Bit position(in range 0-31)= 1

Output:

The given number { 5 } after set the { 1 } bit position =  7

Example2:

Input:

Given Number = 8
Bit position(in range 0-31)= 2

Output:

The given number { 8 } after set the { 2 } bit position = 12

Program to Set nth Bit of a Number in Python

Below are the ways to set the nth bit of the given Number in Python:

Method #1: Using Bitwise |(or) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the bit position as static input and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 5
# Give the bit position as static input and store it in another variable.
bitpositin = 1
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

The given number { 5 } after set the { 1 } bit position =  7

Method #2: Using Bitwise |(or) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the bit position as user input using the int(input()) function and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the bit position as user input using the int(input()) function and 
# store it in another variable.
bitpositin = int(input("Enter some random number = "))
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

Enter some random number = 8
Enter some random number = 2
The given number { 8 } after set the { 2 } bit position = 12

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

Need of Operator Overloading in C++ ?

Need of Operator Overloading

In the previous article, we have discussed about C++ : How to Find Duplicates in a Vector. Let us learn Operator Overloading in C++ Program.

Need of Operator Overloading in C++

1)Operator Overloading

Operator overloading is a feature of object-oriented programming that enables a programmer to redefine a built-in operator to work with user-defined data types.
Let’s pretend we’ve created a class called Integer to handle integer operations. To handle the various operations, we can use the functions add(), subtract(), multiply(), and divide(). However, it is preferable to use operators that correspond to the given operations(+, -, *, and /, respectively) to make the code more understandable and improve readability, i.e. we can substitute the following code with the following code.

2)Example of Operator Overloading (concatenate two strings)

When using the + operator with two integers, for example, the numbers are added, while when using the + operator with two string arguments, the strings are concatenated.

Below is the Implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string string1 = "BTechGeeks";
    string string2 = "Platform";
    // For strings, the + operator is overloaded by default.
    // It will join the strings together.
    string string3 = string1 + string2;
    cout << "concatenated string = " << string3 << endl;
    return 0;
}

Output:

concatenated string = BTechGeeksPlatform

Operators for primitive data types such as int, double, string, and so on are already overloaded. However, we cannot overload user-defined classes.

3)Need of Operator Overloading for a User Defined Class

The overload operator is also available in C++ for user-defined classes.

Assume we have a user-defined class called ComplexNumber, and we have generated two objects of it, i.e.

class ComplexNum
{
    int real;
    int imaginary;
public:
    ComplexNumber(int re, int im) :
            real(re), imaginary(im)
    {}
};

Let’s say we want to use the + operator with two objects, i.e.

ComplexNum cm1(5, 2);
ComplexNum cm2(9, 7);
// calling +(operator) for the above objects
ComplexNumber cm3 = cm1 + cm2;

It will show a compile error, indicating that, like other operators, the + operator is overloaded by default for primitive data types only, not for user-defined classes.
When we use the + operator with ComplexNumber operands, the compiler is stumped.

We must overload a user specified class if we want to use the + operator for it. Let’s look at how to overload the + operator in the ComplexNumber class.

4)How to use a given class to overload an operator

To use operator overloading for user define class it is implemented as below,

operator X(arguments)

Here X represents the operator symbol, such as +, –, /, and so on.
The following are examples of operator functions: either a global function or a function that is a part of a class.

5)Overloading + Operator for Complex Number class

Since the + operator is a binary one, it can accept two arguments.
It takes two arguments, namely two objects of our custom class, and returns a new object of the same class.

This feature now has access to the private members of the user-defined class ComplexNumber. As a result, we must declare it as a friend function, i.e.

Now, if we use the + operator with ComplexNumber class objects, this global overloaded function, i.e.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;

class ComplexNum {
    int real;
    int imaginary;

public:
    ComplexNum(int re, int im)
        : real(re)
        , imaginary(im)
    {
    }
    void print()
    { // printing the real and imaginary part of the complex
      // number
        cout << real << " + " << imaginary << "i" << endl;
    }
    // overloading + operator for complexNum class
    friend ComplexNum operator+(ComplexNum obj1,
                                ComplexNum obj2);
};
// overloading + operator for complexNum class
ComplexNum operator+(ComplexNum object1, ComplexNum object2)
{
    return ComplexNum(object1.real + object2.real,
                      object1.imaginary
                          + object2.imaginary);
}
int main()
{
    ComplexNum cm1(5, 2);
    ComplexNum cm2(9, 7);
    cm1.print();
    cm2.print();
    // calling + opertor for two objects
    ComplexNum cm3 = cm1 + cm2;
    cm3.print();
    return 0;
}

Output:

5 + 2i
9 + 7i
14 + 9i

Here both imaginary and real part of Complex number is added

Similarly we can overload any operator by the same method as given above.

Related Programs:

boost::any Usage in CPP

boostany Usage details

In the previous article, we have discussed about How to Copy all Values from a Map to a Vector in CPP. Let us Learn boost::any Usage in C++ Program.

Boost::any in C++

1)Boost::any

Strongly typed languages, such as C++, require each variable to have a particular type that determines what kind of data it can store. Other programming languages, such as JavaScript, allow developers to store any type of data in variables. In JavaScript, for example, a single variable may contain a string, then a number, and finally a boolean value.

boost::any provides the boost::any class, which, like JavaScript variables, can store arbitrary types of data.

Header file used :
#include<boost/any.hpp>
Syntax:

boost::any variable_name;Variables of type boost::any are not entirely limitless in terms of what they can store; there are some, although minor, preconditions. Any value contained in a boost::any variable must be copy-constructible. As a result, since C/C++ arrays are not copy-constructible, they cannot be stored.

2)Prebuilt Functions of  Boost::Any

  1. clear( ) : It is used to remove the data from a variable.
  2. empty() : It is used to determine whether or not a variable is empty. This function is usually used in conjunction with if-else conditions.
  3. swap( ) : It is used to swap the contents in two variables of any datatype.
  4. type( ) : When we need to know what kind of data a variable contains, we use it.
  5. any_cast( ): This function returns a copy of the variable and is commonly used for printing.
  6. bad_any_cast( ) : Where the data does not fit the template datatype and an error occurs, is commonly used for try and capture blocks.

3)Implementation of boost::any

Below is the implementation:

#include "boost/any.hpp"
#include <bits/stdc++.h>
using namespace std;
int main()
{

    // declaring any data type
    boost::any a, b, c, d;

    // Initializing "a" with some random integer value
    a = 100;

    // Printing the value of a using boost::any_cast
    cout << boost::any_cast<int>(a) << endl;

    // Initializing "b" with some random character value
    b = 'S';

    // Printing the value of b using boost::any_cast
    cout << boost::any_cast<char>(b) << endl;

    // Initializing "c" with some random string value
    c = string("BTechGeeks");

    // Printing the value of c using boost::any_cast
    cout << boost::any_cast<string>(c) << endl;

    // Initializing "d" with some random float value
    d = 98.7423;

    // Printing the value of d using boost::any_cast
    cout << boost::any_cast<double>(a) << endl;

    // Giving integer value to b and providing float as
    // parameter for any_cast
    // it gives error so we used try and catch block
    // to handle the error
    try {
        boost::any b = 100;
        cout << boost::any_cast<float>(b) << endl;
    }
    catch (boost::bad_any_cast& e) {
        cout << "Exception is Caught while converting : "
             << e.what() << endl;
        
    }

    return 0;
}

Output:

100
S
BTechGeeks
Exception is Caught while converting : boost::bad_any_cast: failed conversion using boost::any_cast

Related Programs:

C++ Program to Check if it is Sparse Matrix or Not

Program to Check if it is Sparse Matrix or Not

In the previous article, we have discussed about C++ Program to Print Identity Matrix. Let us learn how to Check if it is Sparse Matrix or Not in C++ Program.

What is a matrix:

A matrix is a rectangular numeric sequence separated into columns and rows. A matrix element, also known as an entry, is a number that occurs in a matrix.

Example:

The matrix shown above has 5 rows and 4 columns, with entries ranging from 1 to 20.

The dimensions of a matrix reflect the number of rows and columns in this sequence.

Because there are 5 rows and 4 columns, this is referred to as a 5*4 matrix.

Sparse Matrix:

A matrix is said to be sparse if the majority of its members are 0. It means that it has a small number of non-zero elements.

To determine if the given matrix is sparse or not, we first count the number of zero members in the matrix. The matrix’s size is then determined. The number of zero items in an array must be more than size/2 for the matrix to be sparse.

Program to Check if it is Sparse Matrix or Not in C++

We will create a program to determine whether or not the given matrix is sparse matrix or not.

Approach:

  • Scan the number of rows and columns of the given matrix and store it in variables row sum and colsum
  • Create a matrix with given dimensions rowsum and colsum
  • Loop through the array, counting the amount of zeros in the array and storing the result in the variable count.
  • Calculate the array’s size by multiplying the number of rows by the array’s number of columns.
  • If the count exceeds size/2, the given matrix is a sparse matrix. That signifies that the majority of the array’s elements are zeroes.
  • Otherwise, the matrix is not sparse.
  • The Exit of the Program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;

// Driver Code
int main()
{
    int rownum, colnum;
    // Scanning number of rows of the given matrix
    cout << "Enter number of rows of the given matrix : "
         << endl;
    cin >> rownum;
    cout << endl;
    // Scanning number of columns of the given matrix
    cout << "Enter number of columns of the given matrix : "
         << endl;
    cin >> colnum;
    cout << endl;
    // creating a matrix with rownum as rows and colnum as
    // columns
    int givenMat[rownum][colnum];
    // scanning all the elements of the matrix
    for (int i = 0; i < rownum; i++) {
        cout << "enter the row elements " << endl;
        for (int j = 0; j < colnum; j++) {
            cout << "enter the element" << endl;
            cin >> givenMat[i][j];
        }
    }
    // taking a variable zeroCount which counts the
    // total number of 0 elements in the given matrix
    // and initializing it to 0
    int zeroCount = 0;
    // traversing the matrix and counting numbeer of zeros
    // in it
    for (int i = 0; i < rownum; i++) {
        for (int j = 0; j < colnum; j++) {
            // cheecking if the element is 0 or not
            // if the element is 0 then increase the zero
            // count by 1
            zeroCount = zeroCount + 1;
        }
    }
    // printing the matrix
    for (int i = 0; i < rownum; i++) {

        for (int j = 0; j < colnum; j++) {

            cout << givenMat[i][j] << " ";
        }
        cout << endl;
    }
    // checking the condition of sparse matrix
    if (zeroCount > (rownum * colnum) / 2) {
        cout
            << "the given matrix givenMat is sparse matrix";
    }
    else {
        cout << "the given matrix givenMat is not a sparse "
                "matrix";
    }

    return 0;
}

Output:

Enter number of rows of the given matrix : 
5
Enter number of columns of the given matrix : 
4
enter the row elements 
enter the element
1
enter the element
0
enter the element
0
enter the element
2
enter the row elements 
enter the element
5
enter the element
0
enter the element
0
enter the element
0
enter the row elements 
enter the element
5
enter the element
0
enter the element
0
enter the element
9
enter the row elements 
enter the element
12
enter the element
0
enter the element
8
enter the element
0
enter the row elements 
enter the element
7
enter the element
0
enter the element
0
enter the element
0
1 0 0 2 
5 0 0 0 
5 0 0 9 
12 0 8 0 
7 0 0 0 
the given matrix givenMat is sparse matrix

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.
Related Programs:

CPP Map: Erase by Value or Callback while Iterating | erase_if for Map

Erase by Value or Callback while Iterating erase_if for Map

In the previous article, we have discussed about Convert First Letter of Each Word of a String to Upper Case in CPP. Let us learn About Map: Erase by Value or Callback while Iterating in C++ Program.

Maps:

C++ STL mapping is Maps (Standard Template Library). Maps are the associative containers in which and key is special and can be inserted or delected, but cannot be altered. Key-related values can be modified.

In this article, we will look at two different methods for removing map elements.

Erasing map elements

There are several ways to erase from map some of them are:

Method #1:Erasing elements by Value

Algorithm:

  • Identify all of the elements and remove the elements (Key value pairs) that match the value in the sector.
  • A template function is created which works for all maps, e.g. std::map<Key, Value> where K & V can be anything.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
template <typename K, typename V>
int erase_Value(std::map<K, V>& elementmap, V given_value)
{
    int number_ofDeletedElements = 0;
    auto itr = elementmap.begin();
    // Traverse the map
    while (itr != elementmap.end()) {
        // checking if the value matches with the given
        // value
        if (itr->second == given_value) {
            number_ofDeletedElements++;
            // erase the element
            itr = elementmap.erase(itr);
        }
        else {
            // increment the iterator
            itr++;
        }
    }
    // return the number of deleted elements
    return number_ofDeletedElements;
}
int main()
{
    // creating a map with string as key and integers as
    // value
    map<std::string, int> elementmap
        = { { "hello", 100 },
            { "this", 200 },
            { "is", 100 },
            { "BTechGeeks", 300 } };

    cout << "Printing the map before deleting " << endl;
    // Printing the map elements
    for (auto element : elementmap)
        cout << element.first << " :: " << element.second
             << endl;
    int givenval = 100;
    // Erasing the elements with the given value
    int deleted_elements_count
        = erase_Value(elementmap, givenval);
    cout << "Number of elements deleted = "
         << deleted_elements_count << endl;

    cout << "Printing the map after deleting " << endl;
    // Print the map elements
    // Printing the map elements
    for (auto element : elementmap)
        cout << element.first << " :: " << element.second
             << endl;
    return 0;
}

Output:

Printing the map before deleting : 
BTechGeeks :: 300
hello :: 100
is :: 100
this :: 200
Number of elements deleted = 2
Printing the map after deleting :
BTechGeeks :: 300
this :: 200

Method #2:Erasing elements using Callback

Algorithm:

  • Iterate through all of the elements, calling the given callback for each one. If the callback returns true, the element is deleted and the process moves on to the next.
  • We’ll write a template function that can operate for any kind of map, such as std::map<K, V>, where K and V can be anything.

Assume we have a string and int map. Delete all elements with even values.

Below is the implementation:

#include <bits/stdc++.h>
#include <functional>
using namespace std;

template <typename K, typename V>
int eraseValue(std::map<K, V>& elementMap,
               bool (*functor)(V))
{
    int number_ofDeletedElements = 0;
    auto itr = elementMap.begin();
    // Traverse the map
    while (itr != elementMap.end()) {
        // checking if the value matches with the given
        // value
        if (functor(itr->second)) {
            number_ofDeletedElements++;
            // erase the element
            itr = elementMap.erase(itr);
        }
        else {
            // Go to next entry in map
            itr++;
        }
    }
    return number_ofDeletedElements;
}
bool isEven(int value)
{
    if (value % 2 == 0)
        return true;
    else
        return false;
}
int main()
{
    // creating a map with string as key and integers as
    // value
    map<std::string, int> elementmap
        = { { "hello", 23 },
            { "this", 46 },
            { "is", 98 },
            { "BTechGeeks", 243 } };
    cout << "Printing the map before deleting : " << endl;
    // Printing the map elements
    for (auto element : elementmap)
        cout << element.first << " :: " << element.second
             << endl;

    // erasing all elements from map  if the value is even
    int deleted_elements_count
        = eraseValue(elementmap, &isEven);
    cout << "Number of elements deleted = "
         << deleted_elements_count << endl;
    cout << "Printing the map after deleting  : " << endl;
    // Print the map elements
    // Printing the map elements
    for (auto element : elementmap)
        cout << element.first << " :: " << element.second
             << endl;
    return 0;
}

Output:

Printing the map before deleting : 
BTechGeeks :: 243
hello :: 23
is :: 98
this :: 46
Number of elements deleted = 2
Printing the map after deleting  : 
BTechGeeks :: 243
hello :: 23

Related Programs:

CPP : How to Reverse a List or Sub-List in Place?

How to reverse a List or sub-list in place

In the previous article, we have discussed about How to Erase Elements from a List in CPP using Iterators. Let us learn How to Reverse a List or Sub-List in Place? in C++ Program.

Lists are sequence containers that allow for the allocation of non-contiguous memory. List traversal is slower than vector traversal, but once a position is found, insertion and deletion are fast. Normally, when we talk about a List, we mean a doubly linked list. We use a forward list to implement a singly linked list.

Given a list, the task is to reverse a list  or sub-list in place

Example:

Input:

stringlist ={ "hello" , "this" , "is" , "BTech" , "Geeks" }

Output:

Before reversing the list : hello this is BTech Geeks 
After reversing the list : Geeks BTech is this hello

Reverse a List or sub-list in place

The member function reverse() is available in std::list() to reverse the list in place

1)Reverse whole list

We can reverse the whole list using reverse() function

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<string> stringlist(
        { "hello", "this", "is", "BTech", "Geeks" });
    cout << "Before reversing the list : ";
    for (auto itr = stringlist.begin();
         itr != stringlist.end(); ++itr)
        cout << *itr << " ";
    cout << endl;
    // reversing the whole list using reverse() function
    stringlist.reverse();
    // printing the list
    cout << "After reversing the list : ";
    for (auto itr = stringlist.begin();
         itr != stringlist.end(); ++itr)
        cout << *itr << " ";
}

Output:

Before reversing the list : hello this is BTech Geeks 
After reversing the list : Geeks BTech is this hello

2)Reverse the sub-list

Let us reverse the first 3 elements of the list .

We can implement it using std::reverse() and std::next() functions.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<string> stringlist(
        { "hello", "this", "is", "BTech", "Geeks" });
    cout << "Before reversing the list : ";
    for (auto itr = stringlist.begin();
         itr != stringlist.end(); ++itr)
        cout << *itr << " ";
    cout << endl;
    // reversing the first 3 items of the list
    reverse(stringlist.begin(),
            next(stringlist.begin(), 3));
    // printing the list
    cout << "After reversing the first 3 items of the list "
            ": ";
    for (auto itr = stringlist.begin();
         itr != stringlist.end(); ++itr)
        cout << *itr << " ";
}

Output:

Before reversing the list : hello this is BTech Geeks 
After reversing the first 3 items of the list : is this hello BTech Geeks

Related Programs:

CPP std::Vector and Iterator Invalidation Example

Vector and Iterator Invalidation Example

In the previous article, we have discussed about CPP Map: Erase by Value or Callback while Iterating | erase_if for Map. Let us learn std::Vector and Iterator Invalidation Example in C++ Program.

Vector:

Vectors are similar to dynamic arrays in that they can resize themselves when an element is added or removed, and the container takes care of their storage. Iterators can access and traverse vector elements since they’re stored in contiguous storage. Data is inserted at the top of vectors. Inserting at the end takes longer since the array may need to be extended at times. There is no resizing, and removing the final variable still takes the same amount of time. Inserting and erasing at the start or within the middle is linear in terms of your time .

Vector and Iterator Invalidation Examples

1)Iterator Invalidation

Iterators in C++ should be used with caution. When we use iterators to iterate over our container, it is possible that the iterator will be invalidated. This may be due to changes in the shape and size of the container when iterating.

When the container to which an Iterator points changes form internally, i.e. moves items from one location to another, the original Iterator always points to the old invalid location, the Iterator becomes invalid.

Vector iterator invalidation occurs when,

  • An element is added to the vector at any point.
  • A vector element is removed.

2)Iterator invalidation when deleting element from vector

Assume an iterator ‘it’ points to the vector position x. Assume that a deletion occurs on that vector, causing its elements to shift from one position to another. If the original iterator ‘it’ still points to the old position, it is invalidated.

For example, in the code below, we use the erase function to delete an element from a vector. The current pointer is invalidated by this erase operation. So, if the same invalidated iterator is used after calling the erase() method, it may result in undefined behaviour.

Implementation:

#include <bits/stdc++.h>
using namespace std;

int main()
{ // creating a vector of type integer
    vector<int> intvec;
    // using for loop to add elements from 1 to 8
    for (int i = 1; i <= 8; i++)
        intvec.push_back(i);
    // print the elements of the vector
    for (auto itr = intvec.begin(); itr != intvec.end();
         itr++)
        cout << (*itr) << "  ";

    cout << endl;

    // Erasing the elements with value 2.
    auto itr = std::find(intvec.begin(), intvec.end(), 2);
    if (itr != intvec.end())
        intvec.erase(itr);

    // Iterator 'itr' is now invalidated because it still
    // points to a deleted spot. So,
    // if you try to use the same iterator again, it can
    // exhibit undefined behaviour.

    for (; itr != intvec.end(); itr++)
        cout << (*itr) << "  ";

    return 0;
}

Output:

1  2  3  4  5  6  7  8  
3  4  5  6  7  8

3)Solution for iterator invalidation when deleting element from vector

Solution:

After calling the erase function, the value of iterator ‘it’ should be modified.
The erase() function, for example, returns an iterator pointing to the new position of the element that came after the last element erased by the same function. Also, if the deleted element was the container’s last element, it restores the container’s end.

// Erasing the elements with value 3.
    auto itr = std::find(intvec.begin(), intvec.end(), 2);
    if (itr != intvec.end())
        itr=intvec.erase(itr);

4)Iterator invalidation when inserting element from vector

When a new variable is added to a vector, it internally changes the components, rendering the old iterators null.

The following are the reasons for element shift:

If an element is added between the two, it shifts all of the right elements by one.
If the new vector size exceeds its current power, it relocates a larger chunk of memory and copies all of the elements there.
As a result, when a new element is added to a vector, the old iterator can become null. Using these old invalidated iterators can lead to unexpected behaviour i.e.

Implementation:

#include <bits/stdc++.h>
using namespace std;

int main()
{ // creating a vector of type integer
    vector<int> intvec;
    // using for loop to add elements from 1 to 8
    for (int i = 1; i <= 8; i++)
        intvec.push_back(i);
    // making iterator to point to first element of vector
    auto itr = intvec.begin();
    // Using for loop and iterator to traveerse and print
    // the elements of vector
    for (; itr != intvec.end(); itr++)
        cout << (*itr) << "  ";

    cout << endl;
    // making iterator to point to first element of vector
    auto itr = intvec.begin();

    // inserting eleemeent 3028 at index 3
    intvec.insert(itr + 3, 1, 3028);

    // Since the old iterator is no longer true, using it as
    // is can
    // result in undefined conduct.

    for (; itr != intvec.end(); itr++)
        cout << (*itr) << "  ";

    return 0;
}

5)Solution for iterator invalidation when inserting element from vector

After calling the insert function, change the value of iterator ‘itr,’ i.e. re-assign it.

// inserting element 3028 at index 3
    intvec.insert(itr + 3, 1, 3028);
// Reinitialize the invalidated iterator to its initial state.
itr = intvec.begin();

Related Programs:

CPP : How to get Element by Index in List

How to get Element by Index in List

In the previous article, we have discussed about How to Reverse a List or Sub-List in Place?. Let us learn How to get Element by Index in List in C++ Program.

Lists are sequence containers that allow for the allocation of non-contiguous memory. List traversal is slower than vector traversal, but once a position is found, insertion and deletion are fast. Normally, when we talk about a List, we mean a doubly linked list. We use a forward list to implement a singly linked list.

Given a list and index, the task is to print the element which is present at given index

Example:

Input:

stringlist ={ "hello" , "this" , "is" , "BTech" , "Geeks" }      index=2

Output:

The value present at index 2 = is

Print element by index in List

Because std::list internally stores elements in a doubly-linked list, the list lacks the random access operator [] for accessing elements by indices. So, to access an element at any kth location, the idea is to iterate from the beginning to the Kth element one by one.

We can access the element by below methods:

1) std::advance() function

To find it in linear time, the STL std::advance() function is used.

Time Complexity : O(n)

Syntax:

advance(InputIterator& it, Distance N)

Parameters:

This function takes two parameters: the iterator to be traversed through the list and the position to which it must be moved. For random access and bidirectional iterators, the position can be negative.

Return:

There is no return type for this function.

Method #1:Using advance() function

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<string> stringlist(
        { "hello", "this", "is", "BTech", "Geeks" });
    // given index
    int index = 2;
    // taking a iterator which points to starting element of
    // the list
    list<string>::iterator itr = stringlist.begin();
    // moving the iterator to index position using advance()
    // function
    advance(itr, index);
    // printing the value
    cout << "The value present at index " << index << " = "
         << *itr;
    return 0;
}

Output:

The value present at index 2 = is

Method #2:Using next() function

C++11 introduces std::next(). It accepts an iterator as well as the position to be advanced. It does not change the passed iterator, but instead uses it to create a new iterator pointing to the nth -1 position of the given iterator and returns it.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<string> stringlist(
        { "hello", "this", "is", "BTech", "Geeks" });
    // given index
    int index = 2;
    // taking a iterator which points to the given index
    // using next() function
    auto itr = next(stringlist.begin(), 2);
    // printing the value
    cout << "The value present at index " << index << " = "
         << *itr;
    return 0;
}

Output:

The value present at index 2 = is

Time Complexity: O(n)
Related Programs:

Finding all Values for a Key in Multimap using Equals_Range

Finding all Values for a Key in Multimap using Equals_Range

Multimap is similar to the map, with several elements having identical keys. In this case, it is NOT necessary to have a single key and mapped value pair. One important thing is to note that multimap always keeps all keys in order. These multimap characteristics make it very useful for competitive programming.

Examples:

Input:

multimap<string, int> givenmap = {
{ "hello", 1 }, { "this", 2 }, { "hello", 3 },
{ "BTechGeeks", 4 }, { "hello", 5 }, { "hello", 6 },
{ "python", 7 },
};

Output:

Displaying all the values for the key hello: 
1
3
5
6

Finding all Values for a Key in Multimap using Equals_Range

1)std::multimap::equal_range

All values of a key can be found in Multimap with its equal_range() member function

It recognises the key as an argument and returns a multimap iterator pair. This returned pair has a range that shows the key entries.

Below is the implementation.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Initializing a multimap with key as string and value
    // as int
    std::multimap<string, int> givenmap = {
        { "hello", 1 },      { "this", 2 },  { "hello", 3 },
        { "BTechGeeks", 4 }, { "hello", 5 }, { "hello", 6 },
        { "python", 7 },
    };
    typedef multimap<string, int>::iterator mapitr;
    // It returns a pair with the range of elements with a
    // 'hello' key.
    pair<mapitr, mapitr> res
        = givenmap.equal_range("hello");
    cout << "Displaying all the values for the key hello: "
         << endl;
    // Traversing over the range
    for (mapitr itr = res.first; itr != res.second; itr++)
        cout << itr->second << endl;
    // Printing number of elements having 'hello' as key
    int hellocount = distance(res.first, res.second);
    cout << "number of elements having 'hello' as key = "
         << hellocount << endl;

    return 0;
}

Output:

Displaying all the values for the key hello: 
1
3
5
6
number of elements having 'hello' as key = 4

2)How to find whether or not a key exists on the same range multimap ()

A range of all elements with the given key returns as equal range(). So we calculate a total number of elements in a given area of iterators in order to determine whether a key does exist or not. You can do it with std:: Algorithm for distance()

If the count is 0 then the key doesn’t exist in given multimap.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Initializing a multimap with key as string and value
    // as int
    std::multimap<string, int> givenmap = {
        { "hello", 1 },      { "this", 2 },  { "hello", 3 },
        { "BTechGeeks", 4 }, { "hello", 5 }, { "hello", 6 },
        { "python", 7 },
    };
    typedef multimap<string, int>::iterator mapitr;
    // It returns a pair with the range of elements with a
    // 'hello' key.
    pair<mapitr, mapitr> res
        = givenmap.equal_range("hello");

    // counting number of hello key  values in given
    // multimap
    int cnt = distance(res.first, res.second);
    if (cnt != 0) {
        cout
            << "number of elements having 'hello' as key = "
            << cnt << endl;
    }
    else
        cout << "Given key doesn't exit in given multimap"
             << endl;

    return 0;
}

Output:

number of elements having 'hello' as key = 4

Related Programs:

Passing Variable Arguments to a Function in Java using Varargs – Tutorial and Example

Passing Variable Arguments to a Function in Java using Varargs

Varargs:

Java has included a feature in JDK 5 that simplifies the creation of methods that require a variable number of arguments. This feature is known as varargs, which is an abbreviation for variable-length arguments. A varargs method is one that accepts a variable number of arguments.
Variable-length arguments could be handled in two ways prior to JDK 5. One method employs overloaded methods (one for each), while another places the arguments in an array and then passes this array to the method. Both are potentially error-prone and necessitate more code. The varargs feature is a better, simpler option.

Passing Variable Arguments to a Function in Java using Varargs

Let’s write a function that accepts variable numbers of the same type, in this case int.

We will use the varargs provided by Java to create this type of function. When declaring a function, use elipsis (…) followed by type to indicate that it can accept a variable number of arguments of a given type.
int findProduct(int... numbs);
This function accepts a variable number of integer arguments and internally converts them to an int array before assigning it to the reference name numbs.

Below is the implementation:

int findProduct(int... numbs)
{
    int product = 0;
    for (int numbers : numbs) {
        product = product * numbers;
    }
    return product;
}

Inside the function body, vararg nums will be treated as an array. This array will contain all of the elements passed to it. It simply iterated through the array, calculated the product of all array elements, and returned the value.

Below is the implementation:

import java.io.*;
import java.lang.*;
import java.util.*;

class Codechef {
    // varargs function which return the product
    int findProduct(int... numbs)
    {
        int product = 1;
        // traversing the varargs and calculating product
        for (int numbers : numbs) {
            product = product * numbers;
        }
        // return the product
        return product;
    }
    public static void main(String[] args)
        throws java.lang.Exception
    { // Taking a object
        Codechef sample = new Codechef();
        // passing varargs to find product function
        int product = sample.findProduct(1, 2, 3, 4);
        System.out.println(product);
        int[] array1 = { 5, 4, 3, 2, 7};
        product = sample.findProduct(array1);
        System.out.println(product);
    }
}

Output:

24
840

Related Programs: