Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was reading some c++ code regarding binary functions and When i read the code, i didnt understand why there was a resize() function. Here is the code:

C++
#include <vector>
#include <iostream>
using namespace std;
template <typename t="">
struct finddivision {
    T operator() (const int& val, const int& val2) {
        if (val > val2)
            cout << val / val2 << endl;
        else if (val2 > val)
            cout << val2/val << endl;
    }
};

int main() {
    vector<int> myvec1 {2, 4, 5,6, 7,2};
    vector<int> myvec2 {6, 16, 55, 36, 77, 22};
    vector<int> holdresult;
    holdresult.resize(myvec2.size());
    transform(myvec1.begin(), myvec1.end(), myvec2.begin(),holdresult.begin(), finddivision<int>());
}


The line where it says: holdresult.resize(myvec2.size()), doesnt make sense to me, because aren't vectors already dynamic and adjust to the size they are given?. Another thing is that, when i comment that line and run the program, i get this return statement:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

So my questions is:
- Why do i need to have that resize() function for my code to work?

What I have tried:

i tried searching for answers and articles regarding my problem, but nothing seemed to match up.
Posted
Updated 19-Sep-21 20:14pm
v2

Start by reading the documentation :
vector::resize at C++ Reference[^]
transform at C++ Reference[^]

It is called there to make sure holdresult has the same number of items that myvec2 does. If it doesn't then transform will not be able to work correctly. That's because it is designed to work with any container so it expects to have storage for the result of the operation available since adding data to a list is different that adding it to a vector.
 
Share this answer
 
Comments
iwanttoaskquestions 20-Sep-21 2:44am    
oh ok thanks
CPallini 20-Sep-21 3:52am    
5.
std::transform requires the result array to have a valid range.
 
Share this answer
 
Comments
iwanttoaskquestions 20-Sep-21 2:45am    
thank you, i understand now

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900