如何在 C++ 中访问对?
How to access pairs in C++?
我不知道如何更恰当地命名这个问题,但基本上就是这样:
我做了一对 pair<int, int> P[20000]
我正在使用 P.first
和 P.second
但是...
当我尝试输入 P.first 时,例如 cin >> P.first[i]
(我是计数器)它不允许我输入。它在编译时调用错误。我该如何解决这个问题?
编辑:得到了我上一个问题的答案,但是新问题:我正在尝试 运行 对 P.second 进行降序排序
sort(P.second, P.second + x, greater<int>());
但它会导致另一个编译错误。我明白为什么会这样,但我该如何解决。基本上,假设这些对是 {{0,0}, {3,2}, {4,-1}, {5,1}}
我想要的结果是 {{3,2}, {5,1}, {0,0}, {4,-1}}
.
我该怎么做?
您的代码中的索引有误。
要更正它,请使用 cin>>P[i].first
而不是 cin>>P.first[i]
。
要对您的条目进行排序,请使用 std:sort
,如下所示:
using Pair = std::pair<int, int>;
auto&& comparator = [](const Pair& lhs, const Pair& rhs){ return lhs.second > rhs.second;};
std::sort( P, P + 20000, comparator );
有关 std::sort
的更多信息,请参阅 here for more information about std::pair
and here。
注意:您需要包含 <algorithm>
头文件才能使用 std:sort
函数。
由于 P
是对数组,其元素 P[i]
也是对。
由于 P[i]
是一对,您可以使用 P[i].first
和 P[i].second
访问它的部分。
第二个问题的答案:
//if you want sort P[] by using first as primiry key and second as second key
std::sort(P, P + 20000, std::greater<std::pair<int, int>>());
//if you wang sort p[] by second only
typedef std::pair<int, int> IIPair;
std::sort(P, P + 20000, [](const IIPair &lhs, const IIPair &rhs){ return lhs.second > rhs.second;});
我不知道如何更恰当地命名这个问题,但基本上就是这样:
我做了一对 pair<int, int> P[20000]
我正在使用 P.first
和 P.second
但是...
当我尝试输入 P.first 时,例如 cin >> P.first[i]
(我是计数器)它不允许我输入。它在编译时调用错误。我该如何解决这个问题?
编辑:得到了我上一个问题的答案,但是新问题:我正在尝试 运行 对 P.second 进行降序排序
sort(P.second, P.second + x, greater<int>());
但它会导致另一个编译错误。我明白为什么会这样,但我该如何解决。基本上,假设这些对是 {{0,0}, {3,2}, {4,-1}, {5,1}}
我想要的结果是 {{3,2}, {5,1}, {0,0}, {4,-1}}
.
我该怎么做?
您的代码中的索引有误。
要更正它,请使用 cin>>P[i].first
而不是 cin>>P.first[i]
。
要对您的条目进行排序,请使用 std:sort
,如下所示:
using Pair = std::pair<int, int>;
auto&& comparator = [](const Pair& lhs, const Pair& rhs){ return lhs.second > rhs.second;};
std::sort( P, P + 20000, comparator );
有关 std::sort
的更多信息,请参阅 here for more information about std::pair
and here。
注意:您需要包含 <algorithm>
头文件才能使用 std:sort
函数。
由于 P
是对数组,其元素 P[i]
也是对。
由于 P[i]
是一对,您可以使用 P[i].first
和 P[i].second
访问它的部分。
第二个问题的答案:
//if you want sort P[] by using first as primiry key and second as second key
std::sort(P, P + 20000, std::greater<std::pair<int, int>>());
//if you wang sort p[] by second only
typedef std::pair<int, int> IIPair;
std::sort(P, P + 20000, [](const IIPair &lhs, const IIPair &rhs){ return lhs.second > rhs.second;});