Vector problem

Hi. I want to first get user input of a whole number n. In the next line n-1 times, numbers which are smaller or equal to n are going to be read. and the number which was left out gets printed.
Example:
5
1 5 4 3

Output:2
I was trying to make an algorithm with a vector, because I am actually learning on how to manage them. I know there are many other algorithms, which are much more easy, but in this case I want vectors.
My program:
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
32
33
#include <iostream>
#include <vector>
#include <algorithm>

int main(){
    std::vector <int> g;
    int num;
    while(1){
        int a=1;
        g.clear();
    std::cin>>num;
    if(num==0){
        break;
    }
    else{
    int b=0;
    for(int n=0;n<num-1;n++){
        std::cin>>b;
        g.push_back(b);
    }
    for(int y=0;y<g.size();y++){
       for(int u=1;u<g.size();u++){
           if(u==g[y]){
               g.erase(std::remove(g.begin(), g.end(), u), g.end());
           }
       }
    }
    }
        std::cout<<g[1]+1<<"\n";
    

}
}


g.erase(std::remove(g.begin(), g.end(), u), g.end());

This erases a number of the vector, so at the end just 1 should be left...
Your algorithm makes absolutely no sense at all.

BTW, you need to learn to properly space out your code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
// istream &in = cin;
   istringstream in( "5\n"
                     "1 5 4 3\n" );

   int N, num, sum = 0;
   in >> N;
   for ( int i = 1; i <= N - 1; i++ )
   {
      in >> num;
      sum += num;
   }
   cout << N * ( N + 1 ) / 2 - sum << '\n';
}



But if you absolutely must use vectors ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
// istream &in = cin;
   istringstream in( "5\n"
                     "1 5 4 3\n" );

   int N, num;
   in >> N;
   vector<bool> B( N, true );
   for ( int i = 1; i <= N - 1; i++ )
   {
      in >> num;
      B[num-1] = false;
   }

   cout << find( B.begin(), B.end(), true ) - B.begin() + 1 << '\n';
}
Last edited on
I did it like this, which is essentially identical to your second solution.
But that first one is great. Always thinking about the mathematical solution!

1
2
3
4
5
6
7
8
9
10
11
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    for (int size; std::cin >> size && size > 0; ) {
        std::vector<bool> v(size);
        for (int n; --size && std::cin >> n; ) v[n - 1] = true;
        std::cout << std::find(v.begin(), v.end(), false) - v.begin() + 1 << '\n';
    }
}

Topic archived. No new replies allowed.