2014-06-15 65 views
-3
vector<pair<int,int> > v; 
for(i=0;i<5;i++){ 
    cin>>b>>c; 
    v.push_back(make_pair(b,c)); 
} 
sort(v.begin(),v.end()); 

是否有可能写入排序功能的比较器,使得v[i].first为递增次序和用于v[i].first类似值进行排序,v[i].second被以递减顺序进行排序?
,如: -
I/P:比较器,用于矢量<对<int,int>>

13 10 
44 15 
13 15 
13 99 
    6 45 

O/P:

6 45 
13 99 
13 15 
13 10 
44 15 
+1

这是C++?请添加一个标签,指定您正在使用的语言。 –

+0

是的,这是可能的,而且很平凡。你只需要编写一个合适的比较函数并将其传递给'std :: sort'。 – juanchopanza

+0

@TomZych:对不起,这是C++。 – Shivam

回答

1

当然,这是很容易。

所有你需要做的是写一个函数与此签名:

bool f(std::pair<int, int> lhs, std::pair<int, int> rhs); 

函数应该返回true当且仅当lhs < rhs

所以,你的标准,lhs小于rhs如果:

  • lhs.first < rhs.first
  • lhs.first == rhs.first && lhs.second > rhs.second

所以,基本上只是把那些在一起,你会得到:

bool mycomparer(std::pair<int, int> lhs, std::pair<int, int> rhs) { 
    if (lhs.first < rhs.first) { 
     return true; 
    } 
    else if (lhs.first == rhs.first && lhs.second > rhs.second) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

这可能是更紧凑写的,但我想保持它的简单性和可读性得到指向对面。 :)

+0

你应该鼓励使用仿函数。 – Csq

+2

@Csq:我应该?为什么? – jalf

1

这是一个紧凑的比较函数对象,你想要做什么:(使用C++ 11层的功能

struct Shivam { 
    typedef std::pair<int, int> const& param_type; 
    bool operator()(param_type lhs, param_type rhs) const { 
     return std::tie(lhs.first, rhs.second) < std::tie(rhs.first, lhs.second); 
    }; 
}; 

而且使用这样的:

std::sort(std::begin(v), std::end(v), Shivam{}); 
+1

请注意,这需要C++ 11。 – Csq

相关问题