N
N
nimbus2142021-10-24 12:36:04
C++ / C#
nimbus214, 2021-10-24 12:36:04

How to fill a vector in a separate function?

How to fill a vector through a function, such a problem that I don’t know what to write in return and the vector is simply not filled.

int ae(int n,vector <int> a) {
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    return 1;
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ronald McDonald, 2021-10-24
@Zoominger

Pass a pointer to a vector to the function.
Stop though, why do you need return in the loop? Remove and try without it.

U
User700, 2021-10-25
@User700

Why such a function? This is one [obviously doing] line in the code.

vector<int> ae (int n) {
  vector<int> a(n);
  for (int& x : a) cin >> x;
  return a;
}

Or
void ae (int n, vector<int>& a) {
  a.resize(n);
  for (int& x : a) cin >> x;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question