221k views
1 vote
Write a C function that takes an STL vector of int values and determines if all the numbers are different from each other (that is, they are distinct).

User Bro
by
5.4k points

1 Answer

2 votes

Answer:

Here is the function:

#include <iostream> //to use input output functions

#include <vector> // to use vector (sequence containers)

#include <algorithm> //use for sequence operations

#include<iterator> //to move through the elements of sequence or vector

using namespace std; //to identify objects cin cout

void DistinctNumbers(std::vector<int> values) { /*function that takes an STL vector of int values and determines if all the numbers are different from each other */

sort(values.begin(), values.end()); //sorts the vector elements from start to end

bool isDistinct = std::adjacent_find(values.begin(), values.end()) == values.end(); //checks for occurrence of two consecutive elements in vector

if(isDistinct==true) // if all numbers are different from each other

{cout<<"Numbers are distinct";}

else //if numbers are duplicate or same

{cout<<"Numbers are not distinct";} }

int main(){ //start of main function

std::vector<int> v = {1,2,3,4,5}; // vector of int values

DistinctNumbers(v); } //function call to passing the vector v to check if its elements are distinct

Step-by-step explanation:

The program that takes an STL vector of int values and the function DistinctNumbers determines if all the numbers are different from each other. It first sorts the contents of the vector in ascending order using sort() method. Then it used the method adjacent_find() to searches the range means from the start to the end of the vector elements, for first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. The result is assigned to a bool type variable isDistinct. It then checks if all the numbers are different and no two adjacent numbers are same. If all the numbers are distinct then this bool variable evaluates to true otherwise false. If the value of isDistinct is true then the message :Numbers are distinct is displayed on screen otherwise message: Numbers are not distinct is displayed in output screen.

Write a C function that takes an STL vector of int values and determines if all the-example-1
User Rowan Miller
by
4.7k points