Nandz
Nandz

Reputation: 45

Runtime Exception in converting set to vector and vector to string in c++

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;
}

Upvotes: 0

Views: 58

Answers (1)

john
john

Reputation: 87959

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); }

Upvotes: 2

Related Questions