The container list may accept another container.
For example a pair.
So we are trying to add pairs inside a list. It will become a list of pairs!
In the snippet below, I’m using only one file.
So just compile and execute it to see the result.
Let’s see this by creating a list of pairs in this tutorial.
The file
/* main.c */
#include <list>
#include <iostream>
#include <string>
class My {
private:
std::list < std::pair > _container;
public:
My() {
std::cout << "My created." << std::endl;
this->containerManager();
}
virtual ~My() {
std::cout << "My destroyed." << std::endl;
}
void containerManager() {
std::cout << "Size of _container = " << this->_container.size() << std::endl;
this->containerAddElement(std::pair("John", "Gray"));
this->containerAddElement(std::pair("William", "Blue"));
this->containerAddElement(std::pair("Charles", "Green"));
std::cout << "Size of _container = " << this->_container.size() << std::endl << std::endl;
this->containerDisplayElements();
this->containerUseFirstElement();
this->containerDisplayElements();
this->containerUseFirstElement();
this->containerDisplayElements();
}
void containerAddElement(std::pair myPair) {
std::cout << "Adding \"" << myPair.first << "\" and \"" << myPair.second << "\" in _container." << std::endl;
this->_container.push_back(std::pair(myPair.first, myPair.second));
}
void containerDisplayElements() {
int k;
std::list < std::pair >::iterator it;
k = 0;
for (it = this->_container.begin(); it != this->_container.end(); ++it) {
std::cout << "*it " << k << " = " << (*it).first << " - " << (*it).second << std::endl;
++k;
}
std::cout << "First element in _container = " << this->_container.front().first << " - " << this->_container.front().second << std::endl << std::endl;
}
void containerUseFirstElement() {
std::cout << "Pop!" << std::endl;
this->_container.pop_front();
}
};
int main() {
My *my = new My();
delete my;
while (1337);
return 0;
}
Result
My created.
Size of _container = 0
Adding "John" and "Gray" in _container.
Adding "William" and "Blue" in _container.
Adding "Charles" and "Green" in _container.
Size of _container = 3
*it 0 = John - Gray
*it 1 = William - Blue
*it 2 = Charles - Green
First element in _container = John - Gray
Pop!
*it 0 = William - Blue
*it 1 = Charles - Green
First element in _container = William - Blue
Pop!
*it 0 = Charles - Green
First element in _container = Charles - Green
My destroyed.
Well done.