c++ – Why doesn't push_back() work?

Question:

Can you explain why push_back() doesn't work?

There is a leaf with numbers at the input, and we must create a dynamic vector from the number of primes in the leaf, and then write them into the vector.

Outputs 0 0 0 0 , but should be 2 3 5 7 . What is the problem?

#include <iostream>
#include <vector>
#include <list>
#include <cmath>


using namespace std;

bool prostoNumer(int n) {
    if (n == 1) return false;
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)return false;
    return true;
}

int shetchik(list<int> lst) {
    try {
        int count = 0;
        for (int n : lst) {
            if (prostoNumer(n) == true) {
                count++;
            }
        }
        if (count > 0) return count;
        else throw 123;
    }
    catch (int i) {
        if (i == 123) cout << "No" << endl;
    }
}

void add(vector<int> vec, list<int> lst) {
    for (int n : lst) {
        if (prostoNumer(n) == true) {
            vec.push_back(n);

        }
    }
}

void print(vector<int> vec) {
    for (int i = 0; i < vec.size(); i++) {
        cout << vec.back() << endl;
        vec.pop_back();
    }
}

int main() {
    list<int> lst = {1, 2, 3, 77, 54, 7, 14, 5, 96};
    vector<int> vect;
    vect.reserve((shetchik(lst)));
    add(vect, lst);
    print(vect);
    system("pause>nul");
    return 0;
}

Answer:

Your push_back works great. But you are passing containers to functions by value. All your changes are applied to the local copy of the container and are lost with that copy when the function ends.

Stop passing heavy objects by value unless absolutely necessary.

How you managed to get the output 0 0 0 0 is not clear. Your container has a size of 0 and the print function will not output anything like this

Scroll to Top