Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you find the summation of elements in a set? [duplicate]

Tags:

c++

add

set

#include <iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;

int main() {
    int i,sum,sum1,n;
    cin>>n;
    vector<int>pre;
    set<int>s1;
    set<int>s2;
    int temp1[n];
    int temp2[n];
    for(i=0;i<n;++i)
        cin>>temp1[i];
    for(i=0;i<n;++i)
        cin>>temp2[i];
    for(i=0;i<sizeof(temp1);++i)
        s1.insert(temp1[i]);    
    for(i=0;i<sizeof(temp2);++i)
        s1.insert(temp2[i]);
    for(i=n;i>=0;--i)
        sum+=i;

    for(i=0;i<s1.size();++i)
        sum1+=s1[i];
    if(sum==sum1)
        cout<<"I become the guy.";
    else
         cout<<"Oh, my keyboard!";
    return 0;
}

ideone link:https://ideone.com/trfOz0 i am trying to add the elements in the set s1 but it seems like this way is not working,how can i do it?

like image 666
BaherZ Avatar asked Mar 15 '23 17:03

BaherZ


2 Answers

You can't index a std::set. It's not built that way. You can check for membership, but you can't just pick the nth element.

In order to take the sum, you'd have to iterate over the set - but not via index, via iterators:

int sum = 0;
for (std::set<int>::iterator it = s1.begin(); it != s1.end(); ++it) {
    sum += *it;
}

Or using std::accumulate:

int sum = std::accumulate(s1.begin(), s1.end(), 0);

Or in C++11:

int sum = 0;
for (int i : s1) {
    sum += i;
}
like image 169
Barry Avatar answered Mar 23 '23 09:03

Barry


  1. You don't initialise your variables sum, and sum1. Using an uninitialised variable is undefined behaviour in C++.

  2. std::set does not define operator[]. So your code will not compile.

The simplest way to sum an STL container like a set is to use

std::accumulate(s1.begin(), s1.end(), 0);

Where the 0 (which must be of the same type as the contains type in the set) is the value you want if the set doesn't contain any elements.

like image 23
Bathsheba Avatar answered Mar 23 '23 07:03

Bathsheba