Does anyone know how to go about answering these questions, a basic explanation
ID: 3904482 • Letter: D
Question
Does anyone know how to go about answering these questions, a basic explanation of how to come about these answers would be greatly appreciated.I have bolded the questions with the answers below. I just am not getting the correct answers when I try to run through these in my head myself.
Question 1.
long a_fn ( long t , long e ) {
return e * e + t ; }
long fn6 ( vector & v ) {
return accumulate ( v . begin () , v . end () , 0 , a_fn ); }
If vector v = {1, 2, 3, 4}, what is the result of calling fn6(v)? The answer is 30
Question 2.
long fn7 ( const vector < vector >& v ) {
long result = 0;
for ( auto r : v ) {
for ( auto c : r ) {
if ( c % 2) result += c ; } }
return result ; }
If vector> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, what is the result of calling fn7(v)? 25
Explanation / Answer
If you have any doubts, please give me comment...
Question 1:
accumulate will pass array or vector to iterate automatically. It's simple like lambda function...
accumulate(v.begin(), v.end(), 0, a_fn);
it will pass vector to the a_fn function, and a_n function will calculate the value according to function statements form vector begin to end.
//here initially init value "t" is 0 and "e" is vector value
long a_fn(long t = 0, long e = 1){
return 1*1 + 0; //1
}
//init value automatically updated and it will pass
long a_fn(long t = 1, long e = 2){
return 2*2 + 1; //5
}
long a_fn(long t = 5, long e = 3){
return 3*3 + 5; //14
}
long a_fn(long t = 14, long e = 4){
return 4*4 + 14; //30
}
finally it will return 30 to fn6, it will return to main function
Question 2:
long fn7 ( const vector < vector >& v ) {
long result = 0;
for ( auto r : v ) { // iterator for rows
for ( auto c : r ) { //iterator for rows
if ( c % 2) //checking the value is odd or not
result += c ;
}
}
return result ;
}
here vector> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} is 2 Dimensional vector, and it will pass to fn7 function...
fn7 funciton will calculate the value that iterate through each and every element if it is calculate the sum of odd values in the vector.
here 1+3+5+7+9 = 25
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.