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' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++] DLL(4)!! ์ฐ์ตํ๊ธฐ ^ใ ^ (0) | 2024.04.02 |
---|---|
[C++] SLL(3)!! ์ฐ์ตํ๊ธฐ ^ใ ^ (0) | 2024.04.01 |
[C++] STL ์ฐ๊ด์ปจํ ์ด๋ STL Associative Container (sets and multisets, maps and multimaps) (3) | 2024.03.29 |
[C++] STL ์์ฐจ ์ปจํ ์ด๋ STL Sequence Container (Vector, List) (0) | 2024.03.29 |
[C++] ostream iterator ์ถ๋ ฅ์คํธ๋ฆผ ๋ฐ๋ณต์ + etc... (0) | 2024.03.29 |