C++ Compare first and second element for all pairs in container
I have vector of pair like this - std::vector < std::pair < int /Val1/, int /Val2/ > > myVector;
What is the efficient way to compare for each pair in 'myVector' first and second element of pair (Val1 and Val2) are same or not.
The only way I could think of is -
bool IsFirstAndSecondSame(vector<pair<T, T>> myVector)
{
for(auto valuePair : myVector)
{
if(valuePair.first != valuePair.second)
return false'
}
return true;
}
Although in example I have used pair of integers, the question is about any pair having first and second element of same type.
Although in example I have used pair of integers, the question is about any pair having first and second element of same type.
You're probably asking about using a templated function like this:
template<typename T>
bool IsFirstAndSecondSame(const vector<pair<T, T>>& myVector) // const
// ^^^^^
// makes no sense
// with free functions
{
for(const auto& valuePair : myVector)
{
if(valuePair.first != valuePair.second)
return false'
}
return true;
}
链接地址: http://www.djcxy.com/p/79202.html
上一篇: 字符数组与char指针在C中有什么区别?