-1

if vector is <0,8> <0,3> <1,4> <2,9> <3,5>

Suppose minimum need to be found considering second key of pair value only, here it will be 3.

output: sample.cpp: In function ‘int main()’: sample.cpp:24:45: error: cannot convert ‘std::pair’ to ‘int’ in initialization int i1=*std::min_element(v.begin(),v.end());

Rishav Kumar
  • 23
  • 1
  • 3

3 Answers3

4

You could either do it by a handcrafted for-loop or using STL std::min_element using a lambda. The way you have used it above is incorrect. Here is the correct way:

auto v = std::vector<std::pair<int,int>>{{0,8},{0,3},{1,4},{2,9},{3,5}};
auto result = *std::min_element(v.cbegin(), v.cend(), [](const auto& lhs, const auto& rhs) {
        return lhs.second < rhs.second;    
    });
std::cout << result.first << " " << result.second  << std::endl; // 0 3

You can try this online here and maybe tinker to understand how the lambda works.
std::min_element will work correctly for native types the way you have used it, but for derived ones like std::pair with the custom condition of only picking the second, you need to supply the criteria via a lambda.
I'd recommend reading up on C++ lambdas - theyre extremely handy in general but especially when needing to supply a custom predicate like in your case! Here is another example: C++ priority queue in ascending order by specific method for objects

tangy
  • 3,056
  • 2
  • 25
  • 42
4

You can use std::min_element and make it test only the second element.

Something like:

std::get<1>(*std::min_element(begin(v), end(v), [](auto lhs, auto rhs) {
  return std::get<1>(lhs) < std::get<1>(rhs)
}));

I'm using get here because I don't know if you are using std::pairs or std::tuples.

As it's still very small structures, no need to pass by const&.

Augustin
  • 2,444
  • 23
  • 24
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
1

So, the vector looks like this:

vector<pair <int, int> > items = { <0,8> <0,3> <1,4> <2,9> <3,5> };

We need to loop through the items to find the smallest second item. To do that:

int saveIndex = 0
//now we can loop through all of the items in the vector
for(int i = 1; i < items.size(); i++)
{
    if(items[saveIndex].second > items[i].second)
    {
        saveIndex = i;
    }
}

//the smallest second value will be found at
int smallestValue = items[saveIndex].second;
cwbusacker
  • 507
  • 2
  • 12