I was just reading about pairs in C when this doubt stroke my mind that how the pairs are stored in memory and id the identifier assigned to the pairs a object or something else. pls explain how an array containing pair uses memory to save the pairs and how can we iterate through the that array, by accessing each pair;
CodePudding user response:
As for the pair itself, if you take a look at the standard library source code you'll just notice, that after cutting all the boilerplate, the for the most trivial case std::pair
is just a simple class template:
template<typename First, typename Second>
struct pair
{
First first;
Second second;
};
Now, all the boilerplate is there to ensure the all the special functions like comparison, assignment, copy construction etc. are performed with minimal overhead. But for the sake of mental model one can think of this simple struct.
As for "array of pairs" - I'm not sure I follow, really.
std::array<std::pair<X,Y>, SIZE>
/std::vector<std::pair<X,Y>>
behaves just as it would for any other type, i.e. it store the pairs in contiguous memory block, end of story.
Same about iteration, there's nothing special about it:
std::array<std::pair<char, int>, 3> pairs{
std::pair{'a', 1},
std::pair{'b', 2},
std::pair{'c', 3}};
for (const auto& p:pairs){
std::cout << p.first << " " << p.second << "\n";
}
CodePudding user response:
Take a look at this example:
#include <iostream>
#include <array>
#include <iterator>
int main( )
{
std::array< std::pair<char, char>, 10 > arrayOfPairs { };
std::cout << "size of array: " << sizeof( arrayOfPairs ) << "\n\n";
for ( size_t idx { }; idx < arrayOfPairs.size( ); idx) // fill the array with
// std::pair objects
{
arrayOfPairs[ idx ] = std::make_pair<char, char>( 'a', 'b' idx );
}
std::cout << "key" << " " << "value" << '\n';
for ( const auto& p : arrayOfPairs ) // print the keys and values
{
std::cout << " " << p.first << " " << p.second << '\n';
}
return 0;
}
Output:
size of array: 20
key value
a b
a c
a d
a e
a f
a g
a h
a i
a j
a k
In this example, each pair object consists of two char
s, so the size is 2 bytes. arrayOfPairs
has the space for 10 pair objects which means that its size is 10 * 2 == 20 bytes. In an std::pair
object, the key and its value are stored besides each other. It acts like a simple struct.