58.8k views
0 votes
Write a function SwapVectorEnds() that swaps the first and last elements of its vector parameter. Ex: sortVector

User Rab
by
7.9k points

1 Answer

0 votes

Answer:

This function is written in C++

void SwapVectorEnds(vector<int>& sortVector){

int vsize = sortVector.size();

sortVector.at(0) = sortVector.at(0) + sortVector.at(vsize - 1);

sortVector.at(vsize - 1) = sortVector.at(0) - sortVector.at(vsize - 1);

sortVector.at(0) = sortVector.at(0) - sortVector.at(vsize - 1);

int i = 0;

while(i<vsize)

{

cout << sortVector.at(i) << " ";

i++;

}

return;

}

Step-by-step explanation:

This defines the function

void SwapVectorEnds(vector<int>& sortVector){

This gets the size of the vector

int vsize = sortVector.size();

The following swap the value of the first element of the vector with the last without using any temporary variable

sortVector.at(0) = sortVector.at(0) + sortVector.at(vsize - 1);

sortVector.at(vsize - 1) = sortVector.at(0) - sortVector.at(vsize - 1);

sortVector.at(0) = sortVector.at(0) - sortVector.at(vsize - 1);

The following iteration prints the new vector

int i = 0;

while(i<vsize)

{

cout << sortVector.at(i) << " ";

i++;

}

return;

}

To call the function from main, use:

SwapVectorEnds(sortVector);