-2

I wrote new code and it works when the user puts 2 numbers but with more then 2 it doesn't work. I think that something has to be changed in the second for loop.



int main() {

    int N;
    cin >> N;
    vector<int>vec;
    int number;
    int firstNumber;
    cin >> firstNumber;
    vec.push_back(firstNumber);

    for (int j = 0; vec.size() < N;j++) {
        cin >> number;
        for (int i = 0; i < vec.size(); i++) {
            if (number == vec[i]) {
                cin >> number;
            }
        }
            vec.push_back(number);
    }
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << endl;
    }
    
    return 0;
}

1 Answers1

1

Your code is overly complicated (and obviously wrong). There is nothing special about the first number, just do all the input in the loop.

This is a way to do it, explanations in the comments:

int main() {

  int N;
  cin >> N;
  vector<int> vec;

  for (int j = 0; vec.size() < N; j++) {
    int number;                 // put variables in the closest possibel scope
    cin >> number;

    bool found = false;         // assume number is not found in the vector
    for (int i = 0; i < vec.size(); i++) {
      if (number == vec[i]) {
        found = true;           // number found
      }
    }

    if (!found)                 // don't add to vector if number has been found
      vec.push_back(number);
  }

  for (int i = 0; i < vec.size(); i++) {
    cout << vec[i] << endl;
  }

  return 0;
}

There is room for improvement:

  • the inner for loop can be improved (this one is easy)
  • you can possibly use more advanced C++ mechanisms (like std::find)
  • vector::size() returns a size_t not an int, therefore the for index variables and N should be size_t instead of int.

Bonus: the last loop can be simplified to this:

for (auto & value : vec) {
  cout << value << endl;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115