与调用 '(std::pair) (unsigned int&, unsigned int)' 不匹配
我不知道以下代码有什么问题,它应该读取数字并将它们的值与位置一起放入成对的向量中,然后对它们进行排序并打印出位置。我用排序删除了部分 - 我认为问题就在那里,但我再次收到编译错误。
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
int main(void)
{
unsigned int n,d,a[65],b[65],s,i,j,t,us=0;
pair<unsigned int,unsigned int> temp;
vector< pair<unsigned int,unsigned int> > v;
cin >> n;
for(i=0;i<n;i++)
{
cin >> t;
temp(t, i+1);
v.push_back(temp);
}
cin >> d;
for(i=0;i<d;i++) cin >> a[i] >> b[i];
for(i=0;i<v.size();i++)
{
cout << v[i].first << " -- " << v[i].second << endl;
}
return 0;
}
请告诉我问题出在哪里。谢谢。
I don't know what's wrong with the follwing code, it should read numbers and put their value with the position together in a vector of pairs and then sort them and print out the positions. I removed the part with sort - i thought the problem was there, but i received an error on compilation again.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
int main(void)
{
unsigned int n,d,a[65],b[65],s,i,j,t,us=0;
pair<unsigned int,unsigned int> temp;
vector< pair<unsigned int,unsigned int> > v;
cin >> n;
for(i=0;i<n;i++)
{
cin >> t;
temp(t, i+1);
v.push_back(temp);
}
cin >> d;
for(i=0;i<d;i++) cin >> a[i] >> b[i];
for(i=0;i<v.size();i++)
{
cout << v[i].first << " -- " << v[i].second << endl;
}
return 0;
}
Please tell me where is the problem. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您唯一使用它的地方是在该循环中,那么在循环外部创建变量并在循环中多次重复使用它通常是不好的形式。仅当构建成本很高并且重新分配比重新创建更便宜时才这样做。一般来说,C++ 变量应该在它们使用的范围内声明,以便更容易阅读程序的每个部分并能够在以后重构它。
对于您的情况,我将完全删除对
temp
的引用,并将 Push_back 调用更改为v.push_back(make_pair(t, i+1))
。It's generally bad form to create a variable outside of a loop and re-use it many times in the loop, if the only place you use it is in that loop. Only do this if the construction cost is high and it's cheaper to re-assign than to re-create. Generally C++ variables should be declared in the scope they are used, to make it easier to read each part of the program and to be able to re-factor it later.
In your case, I would delete the reference to
temp
entirely, and change the push_back call tov.push_back(make_pair(t, i+1))
.问题是
temp(t, i+1);
您需要手动设置第一个和第二个
或者您可以在循环内声明 temp (可能是我会做的)。
或者第二个替代方案,使用 make_pair 辅助函数,并完全取消 temp (感谢 KennyTM 的提醒)
希望这会有所帮助
The problem is
temp(t, i+1);
You need to set the first and second manually
Alternatively you can declare temp inside the loop (probably what I'd do).
Or a second alternate, use the make_pair helper function, and do away with temp completely (thanks to KennyTM for the reminder)
Hope this helps