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());
Run Code Online (Sandbox Code Playgroud)
是否可以为排序函数编写一个比较器,以便v[i].first按升序排序,并且对于 的相似值v[i].first,v[i].second按降序排序?
像:-
i/p:
13 10
44 15
13 15
13 99
6 45
Run Code Online (Sandbox Code Playgroud)
输出:
6 45
13 99
13 15
13 10
44 15
Run Code Online (Sandbox Code Playgroud) 我是 C++ 初学者,遇到以下问题:在我的程序中,我有一个函数,我向该函数传递一个固定大小的数组作为参数。我迭代它并执行一些操作。结果我有 2 个变量 -br和a,我想从函数返回它们。我创建了一对并为其分配了这些值。但是,当我运行整个程序时,编译器会抛出错误 - 无法将 std::pair<> 转换为 int。我想请问为什么会出现这种情况呢?
#include <utility>
using namespace std;
pair <double,double> rez;
//int main() ...
double sumaf(int k[20])
{
for(int i=0; i<20; i++)
{
if(k[i]>0 && k[i]%3==0)
{
a+=k[i];
br++;
}
}
rez.first=a;
rez.second=br;
return rez;
}
Run Code Online (Sandbox Code Playgroud) 我试图打印成对的元素,但它抛出一个错误:"没有匹配的函数调用"
代码:
#include <utility>
#include <iostream>
using namespace std;
int main()
{
pair<int, string> pairVec;
pairVec = make_pair(1, "One");
pairVec = make_pair(2, "Two");
pairVec = make_pair(3, "Three");
for(auto iter:pairVec)
{
std::cout << "First: " << iter.first << ", Second: "
<< iter.second << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如果我有一个vector<pair<int,int> >数据类型,那么通过该对的第一个元素对它进行排序的可接受方式是什么,然后如果第一个是相等的则按秒进行排序?例如,可能是(1,10),(3,3),(7,13),(7,16),(8,1),(8,2),(15,2)等.
我试图输入数据作为整数对的列表,按第一对值排序对,然后是第二个值,然后输出排序的对值;
#include <list>
#include <iostream>
#include <algorithm>
//experiment with list sort of pair
using namespace std;
int main (int argc, char* argv[]){
int N,x,y;
list< pair<int,int> >::iterator it;
list< pair<int,int> > a;
cout<<" number of pairs?"<<endl;
cin >> N;
cout<<"enter pairs, with space between 1st and second of pair"<<endl;
for(int i=0;i<N;++i) {
cin >> x >> y;
a.push_back(make_pair(x,y));
}
cout<<"sorted pairs;"<<endl;
sort(a.begin(),a.end()); // Sorts first the x, then the y-coordinate
for (it=a.begin(); it!=a.end(); ++it) {
cout << " " << …Run Code Online (Sandbox Code Playgroud) 这是我的完整代码:
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define mp make_pair
#define ss second
int main(void) {
int m;
vector <string> grid;
cin >> m;
pair <int,int> foo;
pair <int,int> bar;
// bar =make_pair (10.5,'A');
foo = make_pair (1,2);
cout<<foo.ss<<endl;
for(int i=0; i<m; i++) {
string s; cin >> s;
grid.push_back(s);
int pp = s.find('p');
int mp = s.find('m');
if(pp>=0){
bar = make_pair(pp,i);
}
cout<<pp<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的错误:
prog.cpp: In function 'int main()': …Run Code Online (Sandbox Code Playgroud)