
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find sum of non-repeating (distinct) elements in an arrays in C++
Consider we have an array A with few elements. We have to find sum of all distinct elements in the array. So if the A = [5, 12, 63, 5, 33, 47, 12, 63], then sum of distinct elements is 160. Duplicate elements are simply ignored once it has considered.
We can use the unordered set to solve this problem efficiently. We will run one single for loop and which value comes first time, its add in sum variable and store in hash table that for next time, we will not use this value.
Example
#include<iostream> #include<unordered_set> using namespace std; int getNonRepeatSum(int arr[],int n) { int sum = 0; unordered_set< int > u_set; for (int i=0; i<n; i++) { if (u_set.find(arr[i]) == u_set.end()) { sum += arr[i]; u_set.insert(arr[i]); } } return sum; } int main() { int arr[] = {5, 12, 63, 5, 33, 47, 12, 63}; int n = sizeof(arr)/sizeof(int); cout << "Sum is: " << getNonRepeatSum(arr, n); }
Output
Sum is: 160
- Related Articles
- Product of non-repeating (distinct) elements in an Array in C++
- Sum of all the non-repeating elements of an array JavaScript
- Sum of distinct elements of an array in JavaScript
- Sum of distinct elements of an array - JavaScript
- Find the last non repeating character in string in C++
- Count distinct pairs from two arrays having same sum of digits in C++
- Count distinct elements in an array in C++
- Find a pair of elements swapping which makes sum of two arrays same in C++
- Golang Program to find the Distinct elements from two arrays
- Python Program to find the distinct elements from two arrays
- Maximum sum of increasing order elements from n arrays in C++
- Sum of special triplets having elements from 3 arrays in C++
- First non-repeating in a linked list in C++
- Maximum sum of increasing order elements from n arrays in C++ program
- Find Sum of pair from two arrays with maximum sum in C++

Advertisements