Swapping Of Subranges From Different Containers In C++ - C++ Programming Tutorial
C++ Course / Advanced Topics / Swapping Of Subranges From Different Containers In C++

Swapping Of Subranges From Different Containers In C++

BLUF: Mastering Swapping Of Subranges From Different Containers In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Swapping Of Subranges From Different Containers In C++

C++ is renowned for its efficiency. Learn how Swapping Of Subranges From Different Containers In C++ enables low-level control and high-performance computing in the tutorial below.

Class templates offer significant versatility in accommodating various types as elements. This allows for seamless interchange of elements between a vector and a list, facilitating the swapping of specific elements with the third-last values as per defined criteria. Moreover, it enables the swapping of ranges within two vectors.

What is the std::swap_ranges?

This procedure exchanges the items within defined intervals across two rows. It necessitates four parameters: the beginning and concluding iterators of the initial segment, and the beginning replicator of the subsequent segment. Upon completion of the alteration of the final element, an iterator indicating the element in the second range is provided as output.

Example

Template<class ForwardIterator1, class ForwardIterator2>
ForwardIterator2 swap ranges(ForwardIterator1 first1, ForwardIterator1 last1, forwardIterator2 first2);

Complexity: When swapping a total of n variables, the std::swap_ranges algorithm exhibits a linear complexity of O(n).

Constraints: To prevent any unpredictable outcomes while utilizing std::swap_ranges, make sure that both collections contain an ample number of elements within the designated ranges.

Personalization: When adjustments are necessary for components based on unique operations or scenarios, you have the option to tailor them by utilizing a loop or std::transform function.

Pseudocode:

Example

function swapSubranges(container1, container2, start1, end1, start2, end2):
    // Ensure the ranges are valid
    if start1 >= end1 or start2 >= end2 or end1 > container1.size() or end2 > container2.size():
        return
    // Swap the subranges
    for i from start1 to end1 - 1:
        temp = container1[i]
        container1[i] = container2[start2 + i - start1]
        container2[start2 + i - start1] = temp
// Example usage
vec1=[1,2,3,4,5]
vec2=[10,20,30,40,50]
swapSubranges(vec1,vec2,1,3,1,4)

Example 1:

Let's consider an example to demonstrate how to exchange subranges between different containers in C++.

Example

#include<iostream>
#include<vector>
#include<algorithm>
Int main()
{
	std::vector<int>vec1={1,2,3,4,5};
	std::vector<int>vec2={10,20,30,40,50};
	//swap subrange from vec1[1,3] with subrange from vec2[1,4]
    auto first1 = vec1.begin() + 1;
    auto last1 = vec1.begin() + 3;
    auto first2 = vec2.begin() + 1;
    auto last2 = vec2.begin() + 4;
    std::swap_ranges(first1, last1, first2);
    // Print the results
    std::cout << "vec1 after swapping: ";
    for (const auto& elem : vec1) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    std::cout << "vec2 after swapping: ";
    for (const auto& elem : vec2) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

Example 2:

Let's consider another scenario to demonstrate the exchange of subranges between different containers in C++.

Example

#inlcude<algorithm>
#include<iostream>
#include<list>
#include<vector>
using namespace std; 
int main() 
{ 
	vector<int>v={-1,-5,-3,2,50};
	list<int>lt ={1,5,3,10,5};
	vector<int>v={-1,-5,-3,2,50};
	list<int>lt={1,5,3,10,5};
	/* swap_ranges() swaps the values starting from the beginning 
	to 3rd last values as per the parameters. 
	Hence (-10, -15, -30) are swapped with (10, 50, 30). */
	swap_ranges(v.begin(), v.begin() + 3, lt.begin()); 
	for (int n: v) 
		cout << n << ' '; 
	cout << '\n'; 
	for (int n: lt) 
		cout << n << ' '; 
	cout << endl; 
}

Output:

Example 3:

Let's consider another scenario to demonstrate the exchange of subranges between different containers in C++.

Example

#include<algorithm>
#include<iostream>
#include<list>
#include<vector>
int main(){
	std::vector<int>v1{1,2,3,4,5};
	std::list<int>l1{10,20,30,40,50};
	//Swapping subranges [1,4] of v1 with [1,4]of l1
    auto first1 = v1.begin() + 1;
    auto last1 = v1.begin() + 4;
    auto first2 = l1.begin();
    auto last2 = l1.begin();
    std::advance(first2, 1);
    std::advance(last2, 4);
    std::swap_ranges(first1, last1, first2);
    // Printing the results
    std::cout << "v1 after swap_ranges:\n";
    for (const auto& elem : v1) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    std::cout << "l1 after swap_ranges:\n";
    for (const auto& elem : l1) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

Conclusion:

The std::swap_ranges function in C++ provides a streamlined approach to exchanging subranges between distinct containers. This function offers a convenient and efficient method for transferring elements between containers as it swaps the elements at a consistent position in both containers.

To avoid unpredictable outcomes when employing std::swapranges, verify the validity of the provided ranges and confirm that they do not intersect. It is important to note that std::swapranges operates with a linear time complexity, allowing for efficient swapping of sizable subranges.

In general, std::swap_ranges offers a robust functionality for structuring and handling containers, simplifying the process of exchanging subranges among various C++ sequences.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience