Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a vector as a key works internally in C++?

This SO answers says that STL Map with a Vector for the Key the vector can be used as a key. So when we use a vector as a key. How does that actually work since the key needs to be unique so when we insert another vector with the same elements will the map check for duplicate element by element or the name of the vector does specify something? Like the name of the array represents the base address. So an array can be used as a key since the base address can be used as a key in this case but what is the key in case of a vector. How does it work internally.

Because when I print the name of the vector, I do get an error

vector<int> v;
cout<<v; //error
like image 969
Pulkit Bhatnagar Avatar asked Feb 17 '20 10:02

Pulkit Bhatnagar


1 Answers

There is an overloaded operator < for the class template std::vector.

template <class T, 
class Allocator>
bool operator< (const vector<T, Allocator>& x, const vector<T, Allocator>& y);

that is based on the standard algorithm std::lexicographical_compare.

Here is a demonstrative program.

#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<int> v1 = { 1, 2 };
    std::vector<int> v2 = { 1, 2, 3 };
    std::vector<int> v3 = { 2 };

    std::cout << std::boolalpha << ( v1 < v2 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v2 ), std::end( v2 ) )
             << '\n';                                              

    std::cout << std::boolalpha << ( v1 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';                                              

    std::cout << std::boolalpha << ( v2 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v2 ), std::end( v2 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';                                              

    return 0;
}

Its output is

true
true
true
true
true
true

So the class can be used as a key in map.

By default the class template map uses the function object std::less that in turn uses the operator <

template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map 
{
    //...
};

However there is no overloaded operator << for the class template std::vector.

like image 83
Vlad from Moscow Avatar answered Oct 10 '22 11:10

Vlad from Moscow