0

Hi I have just started learning c++ and i cant seem to make out why this code is giving me a runtime exception while converting a vector to set and set to vector. Please Help!

#include <bits/stdc++.h>
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    vector<int> v;
    for(int i = 0; i < n; i++) { cin >> v[i]; }
    set<int> s(v.begin(), v.end());
    vector<int> v2(s.begin(), s.end());

    if (v2.size() >= 2)
        cout << v2[1];
    else
        cout << "NO";
    return 0;
}
mch
  • 9,424
  • 2
  • 28
  • 42
Nandz
  • 45
  • 6
  • 1
    Take a look on your `set` definition. You're creating a new set for only one value? What is your intention with this variable? – William Prigol Lopes May 27 '20 at 13:13
  • 1
    Please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude May 27 '20 at 13:16
  • I am creating a set so that all the duplicate elements of the vector can be removed and sorted.Then im converting it to a vector so that i can access the second element. – Nandz May 27 '20 at 13:18
  • Regarding your current code, instead of the vector-set-vector conversion you might be interested to learn about the [standard algorithm functions](https://en.cppreference.com/w/cpp/algorithm) available, especially [`std::sort`](https://en.cppreference.com/w/cpp/algorithm/sort) and [`std::unique`](https://en.cppreference.com/w/cpp/algorithm/unique). – Some programmer dude May 27 '20 at 13:18
  • As a side note, this code doesn't throw any exceptions. segfault (which probably happens here) is not an exception in itself. – Kaldrr May 27 '20 at 13:49

1 Answers1

2

This code is wrong

vector<int > v; 
for(int i=0;i<n;i++) {cin>>v[i];}

Your vector is created at size zero, so v[i] is an out of bounds vector access whatever the value of i. Vectors don't grow just because you assign elements to them.

Two possible solutions

1) Create the vector at the right size to begin with

vector<int > v(n); // vector of size n

Or

2) Use push_back to add items to the back of the vector

vector<int > v; 
for(int i=0;i<n;i++) { int t; cin>>t; v.push_back(t); }
john
  • 85,011
  • 4
  • 57
  • 81