ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Swapping Two Standard C++ List With Example

Updated on July 30, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

1. Introduction to Swapping

In any programming language, we may end up having to swap the content of the two variables. If it is a single entity, say two integers. we will end up swapping two values. But, in the case of collections swapping, we must iterate the entire contents and swap the elements between them! The list class of the C++ standard template library provides the function “swap()”, which performs the swapping between two lists. In this article, we will see how it works.

2. Global function to Iterate through each element

The Print_List() global function will take the C++ Standard List as parameter and iterates through each element. On each iteration, it will take the element stored in it and prints that in the console output window. The code for this function is given below:

//ListSort01: Required Includes
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <list>
#include <string>

using namespace std;

//ListSort 02: Function to Print the Values in List
void Print_List(list<int> listParam)
{
	list<int>::iterator listItr;
	printf("\nThe List members are:\n");
	for (listItr = listParam.begin();
		listItr != listParam.end();
		listItr++)
	{
		printf("%d ", *listItr);
	}
}

3. Swap two Standard List - Code Example - Explained

In the main() function, two c++ standard lists are created. We are going to swap the content of these two lists in this example. The code snippet is below:

//3.1 Create lists
list<int> FirstList;
list<int> SecondList;

Once the lists are ready, they are populated with the integer values. The first list is populated with Odd Number values and length of this list is Five. The second list is populated with Even Number values and the length of this list is Four. To populate both the list we used push_back() function of standard c++ list. The code is below:

//3.2 Prepare First List
FirstList.push_back(1);
FirstList.push_back(3);
FirstList.push_back(5);
FirstList.push_back(7);
FirstList.push_back(9);

//3.3 Prepare Second List
SecondList.push_back(2);
SecondList.push_back(4);
SecondList.push_back(6);
SecondList.push_back(8);

Now, we have two C++ standard lists on hand. Before we perform the Swap operation on the standard list, we will print the content of the lists on the console output window. Our global function Print_List() is called twice to print the content of both the lists. On each call, we are passing the list to be printed on the console output window as parameter. Below is the code:

//3.4 Print First and Second List
printf("First List");
Print_List(FirstList);
printf("\nSecond List");
Print_List(SecondList);

Now, it is time to call the swap function. The swap() is a member function of the C++ standard List and which will swap the content of the passed-in list with its own list. For Example, if we call the swap member function on FirstList by passing the SecondList as parameter, the contents of the first list is swapped with the content of the second list. Therefore, the below two function call achieve the same result:

FirstList.swap(SecondList);
SecondList.swap(FirstList);

In our example, we are calling the swap function of the first list and second list is passed as parameter. After the swapping the performed, we are making call to the Print_List() function to print the contents of the List. Have a look at the below depiction:

Swapping two Standard C++ List
Swapping two Standard C++ List | Source

The above picture shows the swapping of the list elements between two lists. When swapping occurs, the list size also gets adjusted. In our case, the length of the first list becomes 4 and length of the second list becomes 5. The code that performs swapping and prints the resultant list is given below:

//3.5 Swap the Lists and Print Contents
FirstList.swap(SecondList);
SecondList.swap(FirstList);
printf("\n\nLists are swapped\n");
printf("-----------------\n");

printf("First List");
Print_List(FirstList);
printf("\nSecond List");
Print_List(SecondList);

Below is the complete example of C++ Standard List Swapping:

//ListSort01: Required Includes
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <list>
#include <string>

using namespace std;

//ListSort 02: Function to Print the Values in List
void Print_List(list<int> listParam)
{
	list<int>::iterator listItr;
	printf("\nThe List members are:\n");
	for (listItr = listParam.begin();
		listItr != listParam.end();
		listItr++)
	{
		printf("%d ", *listItr);
	}
}


//ListSort 03: Swapping Two Lists
void main()
{
	//3.1 Create lists
	list<int> FirstList;
	list<int> SecondList;

	//3.2 Prepare First List
	FirstList.push_back(1);
	FirstList.push_back(3);
	FirstList.push_back(5);
	FirstList.push_back(7);
	FirstList.push_back(9);

	//3.3 Prepare Second List
	SecondList.push_back(2);
	SecondList.push_back(4);
	SecondList.push_back(6);
	SecondList.push_back(8);

	//3.4 Print First and Second List
	printf("First List");
	Print_List(FirstList);
	printf("\nSecond List");
	Print_List(SecondList);

	//3.5 Swap the Lists and Print Contents
	FirstList.swap(SecondList);
	SecondList.swap(FirstList);
	printf("\n\nLists are swapped\n");
	printf("-----------------\n");

	printf("First List");
	Print_List(FirstList);
	printf("\nSecond List");
	Print_List(SecondList);

	_getch();
}

The output of the above program Example is displayed in the below screen-shot:

Program Output of C++ Standard List Swapping
Program Output of C++ Standard List Swapping | Source

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)