profile-img
์ง€๋ฐ์ด์˜ ํ‹ฐ์Šคํ† ๋ฆฌ
images/slide-image

STL Pair 

  • pair combines two values in a single unit
  • pair ํƒ€์ž…์˜ ๋ชจ๋“  ๊ฐ์ฒด๋Š” ๋‘๊ฐœ์˜ ๋ฉค๋ฒ„ ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง - first, second (์ „๋ถ€ public)
  • #include <utility> ๋ฅผ ๊ผญ ๋„ฃ์–ด์•ผ๋Œ 
default constructor pair<T1, T2> pairObj;
overloaded constructor (with two parameters) pair<T1, T2> pairObj(T1, T2);
copy constructor pair<T1, T2> pairObj(otherPairObj);

 

EX1)

#include <utility>
...
void someFuction()
{
	pair<int, double> pair1(3, 5.4);
    	cout << pair1.first() << ", " << pair1.second() <<endl;
}

 

EX2)

#include <utility>

pair<int, double> p1;
p1.first() = 3;
p1.second() = 2.5;

pair<int, double> p2(13, 4.5);
pair<string, int> student("Bob", 123);

cout << student.first();
cout << student.second();

 

EX3)

Pair's memebr variables should be PUBLIC ! The program will CRASH!!!

#include <utility>
...
void someFunction()
{
	pair<int,MyClass> pair1; //default values
    cout << pair1.first() << pair1.second(); 
}

class MyClass
{
	public:
    	...
    private:
    	string str;
        double d;
}

Nested Containers ์ค‘์ฒฉ์ปจํ…Œ์ด๋„ˆ 

  • An STL container can store instances of other containers.
    • A vector of vectors
    • A list of pointers to vectors
    • A map of strings and sets
    • ๋Œ€์ถฉ ์ปจํ…Œ์ด๋„ˆ ์•ˆ์— ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ๋“ค์–ด๊ฐ„๋‹ค๋Š” ๋œป .. 

EX1) Vectors of Vectors

vector<vector<int>> studentGrades = {
		{98, 90, 100},	// student 1
        	{75, 97, 87},	// student 2
        	{96, 74, 88}	// student 3
};

cout << "Total number of students: " <<	studentGrades.size() << endl;
		// studentGrades ๋ฒกํ„ฐ์— ์ €์žฅ๋œ ํ•™์ƒ์˜ ์ˆ˜ -> 3
        
//iterating the elements in a vector of vectors
int row = 0;
for (const auto& students : studentGrades)
{
	cout << "Student " << row << "grades: ";
    for (auto grade : students)
    {
    	cout << grade << " ";
    }
    ++row;
    cout << "\n";
}

 

EX2) Map of Strings and Vectors

map<string, vector<int>> studentGrades = {
            {"Jane", {98, 90, 100}},
            {"Bob", {75, 97, 87}},
            {"Jill", {96, 74, 88}},
            };
            
cout << "Total number of students: " << studentGrades.size() << endl;

for (const auto& grades : studentGrades)
{
    cout << grades.first << ": ";
    for (auto grade : grades.second)
    {
        cout << grade << " ";
    }
    cout << "\n";
}

 

.. ๋€ผ

'เซฎโ‚หถแต” แต• แต”หถโ‚Žแƒโ™ก/coding' Related Articles +