Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
set::swap() in C++ STL
Next article icon

std::swap_ranges in C++

Last Updated : 25 Jul, 2017
Comments
Improve
Suggest changes
Like Article
Like
Report
std::swap is used for swapping of elements between two containers. One of its variation is std::swap_ranges, which as the name suggests is used for swapping the elements within a range. It simply exchanges the values of each of the elements in the range [first1, last1) with those of their respective elements in the range beginning at first2. If we look at its internal working, we will find that this function itself uses std::swap(). Syntax:
  std::swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,                    ForwardIterator2 first2);    Here, first1, last1 and first2 are forward iterators.  Returns: It returns an iterator to the last element swapped in the second sequence.  
CPP
// C++ program to demonstrate  // the use of std::swap_ranges #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { 	// Declaring first vector 	vector<int> v1; 	int i; 	     // v1 contains 0 1 2 3 4 5 6 7 8 9 	for (i = 0; i < 10; ++i)  	{ 		v1.push_back(i); 	} 	  	// Declaring second vector 	// v2 contains 100 100 100 100 100 	vector<int> v2(5, 100); 	 	// Performing swap 	std::swap_ranges(v1.begin() + 3, v1.begin() + 7, v2.begin());  	// Displaying v1 after swapping 	for (i = 0; i < 10; ++i)  	{ 		cout << v1[i] << " "; 	}  	cout << "\n"; 	 	// Displaying v2 after swapping 	for (i = 0; i < 5; ++i)  	{ 		cout << v2[i] << " "; 	}  	return 0; } 
Output:
  0 1 2 100 100 100 100 7 8 9  3 4 5 6 100  
Here, in this program we have swapped elements from v1 starting at v1.begin()+3 till v1.begin()+7, with the values starting from v2.begin(), so in place of swapping the whole vector, we have performed swapping in a range. Where can it be used ? It can be used when we have to find whether a given container contains the same element in its first half as well as in the second half as well, i.e., whether both the halves are identical to each other or not. CPP
// C++ program to demonstrate  // the use of std::swap_ranges #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { 	// Here 5 is the central element and the two halves 	// on its either side contain the same elements 1 2 3 4 	vector<int> v1 = { 1, 2, 3, 4, 5, 1, 2, 3, 4 };  	int i;  	// Declaring second vector and making it equal to v1 	vector<int> v2 = v1;  	// Here there is no central element and the two halves 	// are 1 2 3 4 and 1 2 3 5 which are different 	vector<int> v3 = { 1, 2, 3, 4, 1, 2, 3, 5 }; 	  	// Declaring fourth vector and making it equal to v3 	vector<int> v4 = v3;  	// Performing swap between two halves of vector v1 	if (v1.size() % 2 == 0) 		std::swap_ranges(v1.begin(), v1.begin() + (v1.size() / 2), 						v1.begin() + v1.size() / 2);  	else 		std::swap_ranges(v1.begin(), v1.begin() + v1.size() / 2, 						v1.begin() + (v1.size() / 2) + 1);  	if (v1 == v2)  	{ 		cout << "Yes"; 	} else  	{ 		cout << "No"; 	}  	// Now, Performing swap between two halves of vector v3 	if (v3.size() % 2 == 0) 		std::swap_ranges(v3.begin(), v3.begin() + (v3.size() / 2), 						v3.begin() + v3.size() / 2);  	else 		std::swap_ranges(v3.begin(), v3.begin() + v3.size() / 2, 						v3.begin() + (v3.size() / 2) + 1);  	cout << "\n";  	if (v3 == v4)  	{ 		cout << "Yes"; 	} else  	{ 		cout << "No"; 	}  	return 0; } 
Output:
  Yes  No  
Explanation of code: Here, in this code, we have declared a vector and then assigned it to another vector, and then in the first vector, we are swapping values in the first half with the second half depending upon whether it contains odd no. of elements or not. If after swapping the values, the new first vector is same as second vector (old first vector), this means that both the halves are same. So, in the first vector 1 2 3 4 5 1 2 3 4, it contains same element in both the halves, so Yes is printed, whereas in second vector 1 2 3 4 1 2 3 5, second half contains one different element than first half, i.e., 4 in place of 5, so No is printed. Time Complexity: It is linear in the distance between first and last.

Next Article
set::swap() in C++ STL

M

Mrigendra Singh
Improve
Article Tags :
  • Misc
  • C++
  • STL
  • cpp-algorithm-library
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

  • std::iter_swap in C++
    std::swap is used for swapping of elements between two containers. One of the other way of doing this same thing is facilitated by std::iter_swap, which as the name suggests is used for swapping the elements with the help of an iterator. It simply exchanges the values of the elements pointed to by t
    3 min read
  • set::swap() in C++ STL
    Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::swap() This func
    2 min read
  • list::swap() in C++ STL
    Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::swap()This function is used to swap the con
    2 min read
  • stack swap() in C++ STL
    Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only. stack::swap()This function is used to swap the contents of one stack with another stack of same type but the size may vary. S
    2 min read
  • queue::swap() in C++ STL
    Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::swap() swap() fun
    2 min read
  • multimap::swap() in C++ STL
    multimap::swap() is used to swap the contents of one multimap with another multimap of same type and size. Syntax:- multimap1.swap(multimap2) Parameters : The name of the multimap with which the contents have to be swapped. Result : All the elements of the 2 multimap are swapped. Examples: Input: mu
    2 min read
  • std::prev in C++
    std::prev returns an iterator pointing to the element after being advanced by certain number of positions in the reverse direction. It is defined inside the header file iterator. It returns a copy of the argument advanced by the specified amount in the backward direction. If it is a random-access it
    5 min read
  • std::next in C++
    std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file . It does not modify its arguments and returns a copy of the argument advanced by the specified amount. If it is a random-access iterator, the function uses ju
    4 min read
  • rotate() in C++ STL
    In C++, rotate() is a built-in function used to rotate the elements of a range in left or right direction such that the element pointed to by a specified iterator becomes the new first element of the range. Let's take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h> using namespace
    4 min read
  • is_sorted() in C++ STL
    In C++, is_sorted() is a built-in function used to check whether the element of the given range is sorted or not in ascending order. In this article, we will learn about is_sorted() function in C++. Let’s take a quick look at a simple example that illustrates is_sorted() method: [GFGTABS] C++ #inclu
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences