vector sort and erase

In the following test cases why is the erase function being dependent on sort function?that is when i comment the sort function the letter 3 is not erased properly and has 2 occurences ??



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std ;

int main()
{
    int test_cases;
    int number_in_each_test_case;
    int number;
    vector<int> numbers;
    cin>> test_cases;
    
    while (test_cases--) {
        cin>>number_in_each_test_case;
        while(number_in_each_test_case--){
            cin>>number;
            numbers.push_back(number);
            numbers.erase(unique(numbers.begin(), numbers.end()),numbers.end());
           sort(numbers.begin(),numbers.end());
        }
        }
    
    for(auto it  = numbers.begin(); it!=numbers.end(); it++ ){
        cout<<*it<<" ";
    }
    }




sample input

2
2
1 3
3
2 3 4

with sort :
http://cpp.sh/6b5l

without sort :
http://cpp.sh/7o3g
Last edited on
With the sort:
2
2
1 3
3
2 4 3
=====
1 2 3 3 4

So, no, it does not work properly even with the sort.

The std::unique condenses only consecutive repeating values. It will do nothing for sets like {2 3 2}.

Overall, why do you erase after each new value? It would make more sense to not push_back a duplicate at all.
IF numbers does not contain number
THEN add number to numbers


If you want to use the erase, then read all values first, and sort+unique+erase the whole set once.
its working properly with the sort... the output is 1 2 3 4 ? its not 1 2 3 3 4

The std::unique condenses only consecutive repeating values. It will do nothing for sets like {2 3 2}.


This I didn't know ,thanks!
Last edited on
Topic archived. No new replies allowed.