'Compare vector<int> with no name

#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;

int main()
{
    std::list<int> list{ 1, 2, 3, 4, 5 };
    std::vector<int> vec1{ 1, 2, 3, 4, 5 };
    std::vector<int> vec2{ 1, 2, 3, 4 };
    if(vector<int>(list.begin(), list.end()) == vec1)
    {
        cout << "haha";
    }
    return 0;
}

There is no name in vector<int>(list.begin(), list.end()). How is it possible to compare vector<int> with no name and vec1.

c++


Solution 1:[1]

How is it possible to compare vector with no name and vec1.

std::vector has overloaded operator== as a non-member function.

template< class T, class Alloc >

bool operator==( const std::vector<T,Alloc>& lhs,
                 const std::vector<T,Alloc>& rhs );

This means that when you wrote:

vector<int>(list.begin(), list.end()) == vec1

a temporary std::vector<int> object is created and is passed as the first argument to the above shown overloaded operator== while vec1 is passed as the second argument to the same overloaded operator== and thus the comparison succeeds. In other words, the first parameter lhs is bound to the temporary std::vector<int> while the second parameter rhs is bound to vec1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana