Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Assume a list has the following element: write a function to interchange the first two elements in the right partition of a list. Please help

Assume a list has the following element:

write a function to interchange the first two elements in the right partition of a list.

Please help to fix the code!

#include #include

template void interchangeFirstTwo(std::list& list) { if (list.size() < 2) return; typename std::list::iterator it = list.begin(); Elem value1 = *it; ++it; Elem value2 = *it; list.erase(list.begin(), std::next(list.begin(), 2)); list.insert(list.begin(), value2); list.insert(list.begin(), value1); }

int main() { std::list list = { 2, 23, 15, 5, 9 };

std::cout << "Original list: "; for (int value : list) { std::cout << value << " "; } std::cout << std::endl;

interchangeFirstTwo(list);

std::cout << "After interchanging first two elements: "; for (int value : list) { std::cout << value << " "; } std::cout << std::endl;

return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions