Boostalgorithmnone Of Equal In C++ Library - C++ Programming Tutorial
C++ Course / STL Algorithm / Boostalgorithmnone Of Equal In C++ Library

Boostalgorithmnone Of Equal In C++ Library

BLUF: Mastering Boostalgorithmnone Of Equal In C++ Library is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Boostalgorithmnone Of Equal In C++ Library

C++ is renowned for its efficiency. Learn how Boostalgorithmnone Of Equal In C++ Library enables low-level control and high-performance computing in the tutorial below.

The Boost C++ Libraries consist of a series of open-source libraries that have undergone peer review and are designed to expand the features of C++. Within these libraries is the Boost. Algorithm library, offering a range of algorithms to improve the existing capabilities of standard C++. An example of one of these algorithms is boost::algorithm::noneofequal, which is included in the Boost library's collection of C++11 algorithms. This particular algorithm offers a simple and effective method for identifying whether none of the elements within a specified range are equal to a particular value.

Purpose and Utility

The boost::algorithm::noneofequal function is designed to verify the absence of a particular value within a set of elements. This functionality proves beneficial in multiple contexts, including validating user input, maintaining data consistency, or eliminating undesired values from a collection. Employing this algorithm enables programmers to sidestep the need for manual iterations and if-else statements, resulting in more compact, understandable, and error-resistant code.

The Boost library includes the Boost algorithm, which enriches regular algorithms with features such as boost::algorithm::noneofequal. This feature simplifies the process of verifying the absence of a specific value among a set of elements. It functions akin to std::none_of in the C++ Standard Library but includes extra tools and enhancements. The primary goal of Boost algorithms is to simplify common programming operations by delivering effective and dependable algorithms that go beyond the capabilities of the standard library. This ensures resilience and adaptability in C++ software development.

The boost::algorithm::noneofequal Function is a templated function that works on a range of elements indicated by two iterators, denoted as first and last. These iterators define the start and conclusion of the specified range to be examined. It also requires a value of type T for comparison with each element within the range. Upon execution, the Function produces a boolean outcome: true if none of the elements in the range match the provided value, and false if at least one element matches the value.

Function Signature

The signature of the boost::algorithm::noneofequal function is:

Example

namespace boost { namespace algorithm {
    template<typename InputIterator, typename T>
    bool none_of_equal(InputIterator first, InputIterator last, const T& value);
}}

The InputIterator denotes the kind of iterator used to signify the scope of elements that need validation.

The data type of these values should be compared with the elements within the specified range.

An iterator pointing to the start of the range.

last: An iterator indicating the conclusion of the range.

value: The value to be compared with the elements within the specified range.

How It Works

The function loops through the range [first, last) and checks each element against the specified value. When it encounters an element that matches the value, it returns false. If none of the elements match the value, it returns true.

Approach-1:Using Manual loop

The traditional loop method is a fundamental and commonly applied strategy in programming to validate conditions over a series of items. It requires going through every item in a group (like an array, vector, or list) and examining each item to see if it satisfies a particular requirement. In this scenario, the requirement is to confirm that no item within the range matches a specific value.

Program:

Example

#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <string>
#include <sstream>
#include <iterator>
// Function template to check if none of the elements in the Container are equal to the specified value
template <typename Container, typename T>
bool noneOfEqual(const Container& container, const T& value) {
    for (const auto& element : container) {
        if (element == value) {
            return false; // If any element is equal to the specified value, return false
        }
    }
    return true; // If no elements are equal to the specified value, return true
}
//Function to read a sequence of integers from the User and store them in the specified Container
template <typename Container>
void readInput(Container& container) {
    std::string input;
    std::cout << "Enter a sequence of integers (separated by spaces): ";
    std::getline(std::cin, input);
    std::istringstream stream(input);
    std::copy(std::istream_iterator<typename Container::value_type>(stream),
              std::istream_iterator<typename Container::value_type>(),
              std::back_inserter(container));
}
// Main Function
int main() {
    //User selects the container type
    std::cout << "Select container type (1: vector, 2: list, 3: deque): ";
    int choice;
    std::cin >> choice;
    std::cin.ignore(); // Ignore the newline character left in the buffer
    //Container to hold the User's input
    if (choice == 1) {
        std::vector<int> vec;
        readInput(vec);
        int value;
        std::cout << "Enter the value to check: ";
        std::cin >> value;
        if (noneOfEqual(vec, value)) {
            std::cout << "None of the elements are equal to " << value << "." << std::endl;
        } else {
            std::cout << "At least one element is equal to " << value << "." << std::endl;
        }
    } else if (choice == 2) {
        std::list<int> lst;
        readInput(lst);
        int value;
        std::cout << "Enter the value to check: ";
        std::cin >> value;
        if (noneOfEqual(lst, value)) {
            std::cout << "None of the elements are equal to " << value << "." << std::endl;
        } else {
            std::cout << "At least one element is equal to " << value << "." << std::endl;
        }
    } else if (choice == 3) {
        std::deque<int> deq;
        readInput(deq);
        int value;
        std::cout << "Enter the value to check: ";
        std::cin >> value;
        if (noneOfEqual(deq, value)) {
            std::cout << "None of the elements are equal to " << value << "." << std::endl;
        } else {
            std::cout << "At least one element is equal to " << value << "." << std::endl;
        }
    } else {
        std::cerr << "Invalid choice." << std::endl;
    }
    return 0;
}

Output:

Output

Select container type (1: vector, 2: list, 3: deque): 1
Enter a sequence of integers (separated by spaces): 23 24 32 54 45
Enter the value to check: 32
At least one element is equal to 32.

Explanation:

The provided example demonstrates a comprehensive implementation of the manual loop approach to check if none of the elements in a container are equal to a specified value. This implementation is designed to handle different types of containers (vector, list, deque) and incorporates user interaction to make the program more dynamic. Here's a detailed explanation of each part of the code:

  • Headers and Namespace The code starts by including several standard headers: <iostream> for input/output operations. <vector>, <list>, and <deque> for different container types. <string> and <sstream> for string manipulation and stream operations. <iterator> for working with iterators. The standard namespace std is implicitly used throughout the code for convenience.
  • Function Template noneOfEqual The function template noneOfEqual is the core of this implementation. It takes a container of any type and a value of the same type as the elements in the Container. The Function uses a range-based loop to iterate through each element in the Container. For each element, it checks if the element is equal to the specified value. If an equal element is found, the Function returns false immediately, indicating that not all elements are unequal to the specified value. If the loop completes without finding any equal element, the Function returns true, indicating that none of the elements are equal to the specified value. This Function is flexible and reusable for different container types due to the use of templates.
  • Function Template read input The readInput function template is designed to read a sequence of integers from the User and store them in a specified container. It prompts the User to enter a sequence of integers separated by spaces. The input is read as a single line of text using std::getline and then processed using std::istringstream to extract individual integers. The std::copy algorithm and iterators are used to insert these integers into the Container. This Function abstracts the input reading process, making the main Function cleaner and more readable.
  • Main Function The main Function begins by prompting the User to select a container type: vector, list, or deque. This is done using a simple integer input, which determines which Container to use for storing the integers. Depending on the User's choice, the appropriate Container is initialized, and the readInput Function is called to populate the Container with integers provided by the User. Next, the User is prompted to enter a value to check against the elements in the Container. The noneOfEqual Function is then called with the Container and the specified value as arguments. The Function's return value is used to determine the output message. If the Function returns true, it means none of the elements are equal to the specified value, and an appropriate message is displayed. Otherwise, a message indicating that at least one element is equal to the specified value is displayed.
  • Complexity Analysis:

The code example illustrates the manual iteration method for verifying whether none of the items in a collection are identical to a given value. Let's delve into the time and space efficiency of the noneOfEqual function, as well as the entire software application.

Time Complexity

The

  1. noneOfEqual function has a time complexity of O(n), where n represents the number of elements in the input.

The noneOfEqual Function examines each item in the Container and checks it against a given value. The efficiency is based on the quantity of elements in the Container, represented as n.

Best Case (O(1)): The optimal situation arises when the initial element in the Container matches the specified value. In this scenario, the Function will promptly return false following the initial comparison, leading to a time complexity of O(1).

Worst Scenario (O(n)): The most unfavorable situation arises when none of the items in the Collection match the given value. The Operation will cycle through all n elements, conducting n comparisons, leading to a time complexity of O(n).

Average Scenario (O(n)): Typically, the Function will be required to inspect approximately half of the elements within the Container in order to locate an element that matches the specified value (or determine its absence). Consequently, the average computational complexity remains O(n).

  1. analyze input Function:

The readInput Function retrieves a series of whole numbers from the User and adds them into the Container.

The Function utilizes std::getline for reading a line of input, which requires O(m) time, with m representing the input string's length.

Following that, it employs std::istringstream for handling the input and std::copy for placing the integers into the Container. Every insertion action has a constant time complexity of O(1), and the Function executes n insertions, with n representing the quantity of integers in the input. Consequently, the time complexity for insertion is O(n).

Overall, the time complexity of parsing input is O(m + n), with m representing the input string's length and n representing the count of integers.

  1. Primary Function:

The primary Operation requests input from the User to choose a specific type of storage and stores the input in the selected Container. These actions have a constant time complexity. Following this, the function invokes the noneOfEqual Method, which operates with a time complexity of linear order.

In general, the time complexity of the primary function is primarily influenced by the readInput and noneOfEqual functions, leading to a complexity of O(m + n).

Space Complexity

The

  1. noneOfEqual function has a space complexity of O(1), indicating that it requires a constant amount of space regardless of the input size.

The space complexity of the noneOfEqual Function depends on the storage needed for the Container and the specific value.

The Container is passed by reference, eliminating the need for extra memory allocation within the Function.

The designated data is transmitted by value, necessitating O(1) storage.

Auxiliary Memory: The function requires a fixed quantity of extra space for managing the loop variable and comparison operation. Therefore, the auxiliary space complexity is O(1).

The space complexity of the noneOfEqual Function remains constant at O(1).

  1. readInput Function:

The space efficiency of the readInput Function depends on the storage space needed for both the input string and the Container data structure.

The provided input string necessitates O(m) memory space, where m represents the input's length.

Container: The storage unit holds a set of n integers, utilizing O(n) space.

Auxiliary Memory: The method utilizes an istringstream instance and iterators, both of which demand constant O(1) space complexity.

Overall, the space efficiency of the readInput Function amounts to O(m + n).

  1. Entry Point Function:

The primary Function allocates a fixed quantity of memory for variables like selection and data, resulting in O(1) space complexity.

It invokes the readInput and noneOfEqual functions, with readInput having a space complexity of O(m + n) and noneOfEqual having a space complexity of O(1).

In general, the space efficiency of the primary Function is primarily influenced by the readInput Function, leading to a complexity of O(m + n).

Approach-2: Using std::none_of

An alternative method for verifying that none of the elements within a container match a specific value involves utilizing the std::none_of standard library algorithm, which was introduced in C++11. This strategy offers a more succinct and clear solution compared to implementing a manual loop.

The std::none_of algorithm verifies if no elements within a range meet a specified predicate. It requires three parameters: the start of the range, the end of the range, and a predicate function or lambda. When no elements fulfill the predicate, it yields true; otherwise, it gives false.

Program:

Example

#include <vector>
#include <iostream>
#include <algorithm>
bool noneOfEqual(const std::vector<int>& vec, int value) {
    return std::none_of(vec.begin(), vec.end(), [value](int element) {
        return element == value;
    });
}
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int value = 6;
    if (noneOfEqual(vec, value)) {
        std::cout << "None of the elements are equal to " << value << "." << std::endl;
    } else {
        std::cout << "At least one element is equal to " << value << "." << std::endl;
    }
    return 0;
}

Output:

Output

None of the elements are equal to 6.

Explanation:

The code snippet is a simple C++ program that uses the standard library algorithm std::none_of to determine if none of the elements in a given vector are equal to a specified value. It demonstrates how modern C++ features, such as lambda expressions and standard algorithms, can be used to write concise and readable code.

  • Header Files #include <vector>: This header file is included to use the std::vector Container, which is a dynamic array that can change size. #include <iostream>: This header file allows for input and output operations using std::cin, std::cout, and std::cerr. #include <algorithm>: This header file provides access to various algorithms, including std::none_of.
  • Function noneOfEqual The noneOfEqual Function is designed to determine if none of the elements in a given vector (vec) are equal to a specified value (value). Here's how it works: Parameters: Vec: This parameter is a constant reference to a vector of integers (std::vector<int>). It represents the Container of integers in which we want to search for the specified value. Value: This parameter is of type int and represents the value we are checking against the elements in the vector. Algorithm: The Function utilizes the std::noneof algorithm from the C++ Standard Library, which is specialized for sequences like vectors. std::noneof takes three arguments: vec.begin and vec.end, which define the range of elements to search through in the vector, and a lambda function value { return element == value; }.
  • Inside the lambda function: The element represents each element in the vector as the algorithm iterates through them. The lambda function checks if the element is equal to the value. It returns true if the element equals value, indicating that at least one element matches the value. It returns false otherwise.
  • Return Value: The noneOfEqual Function returns the result of std::noneof, which is a boolean (true or false). If std::noneof returns true, it means none of the elements in the vector vec are equal to the value. If std::none_of returns false, it means at least one element in the vector vec is equal to the value.
  • Main Function The main Function demonstrates the usage of the noneOfEqual Function: Vector Initialization: A vector vec is initialized with the values {1, 2, 3, 4, 5}. This vector serves as the Container in which we will check for equality with value. Value to Check: An integer variable value is set to 6. We will check the elements in vec against this value. Condition Check: The if statement checks the result of calling noneOfEqual(vec, value). If noneOfEqual returns true, it means none of the elements in vec are equal to value, and it prints "None of the elements are equal to 6.". If noneOfEqual returns false, it means at least one element in vec is equal to value, and it prints "At least one element is equal to 6.". Execution: Finally, the main Function returns 0, indicating successful execution of the program.
  • Complexity Analysis:

Analyzing the time and space complexity of the noneOfEqual Function and the entire software entails evaluating the efficiency of the algorithms used and the memory allocation during its runtime.

Time Complexity

noneOfEqual Function:

The noneOfEqual Function makes use of the std::none_of algorithm provided by the C++ Standard Library. Let's examine the breakdown of time complexity:

Iterating through Elements: The std::none_of function loops through every element within the vector named vec, starting from vec.begin up to vec.end.

Iterating across n items within a vector (vec) results in a time complexity of O(n), with n representing the total count of elements stored in the vector.

For every item, the lambda expression value { return item == specific_value; } is executed.

Time Complexity: The lambda function's execution includes a comparison that runs in constant time (element == value), denoted as O(1).

Overall Time Complexity: Taking into account all these aspects, the primary factor influencing the time complexity of noneOfEqual is the traversal of the vector, resulting in a time complexity of O(n).

Main Function:

The primary function, named noneOfEqual, is executed once and carries out various operations that take constant time such as initializing vectors, assigning values, and performing conditional checks. Consequently, the time complexity of the main function is predominantly influenced by the time complexity of noneOfEqual.

Space Complexity

noneOfEqual Function:

Memory Consumption: The noneOfEqual Function works on the vector vec utilizing a lambda expression. This lambda expression captures values individually ([value]), functioning without the need for extra memory allocation.

Space Complexity: The space complexity remains at O(1) for the extra space utilized by the lambda function. It merely maintains a fixed number of variables (value) on the stack, thereby not increasing the space complexity.

Main Function:

Memory Usage: The primary function sets up a vector named vec with n whole numbers and reserves memory for these values (O(n)).

Space Utilization: Thus, the space complexity of the primary Function is O(n), with n representing the quantity of elements within the vector.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience