c++ 不存在合适的构造函数来从 "int" 转换为 "std::pair<int, int>"

c++ no suitable constructor exists to convert from "int" to "std::pair<int, int>"

我无法解决此错误。当我搜索此错误时,我在 Google 上运气不佳。

no suitable constructor exists to convert from "int" to "std::pair<int, int>"

#include <utility>

using namespace std;

pair<int, int> solve(int s, int g)
{
    return s % g != 0 ? (-1, -1) : (g, s - g);
}

错误波浪线在 return 的第一个 s 下面,它正在检查...

s % g != 0

我不知道如何解决这个问题。在 C# 中,这会起作用。

public static (int, int) solve(int s, int g) => s % g != 0 ? (-1, -1) : (g, s - g);

(a, b) 而不是 一对,它是一个使用逗号运算符的表达式。它 计算 ab,但表达式的 结果 b只要。这就是为什么它抱怨它无法将您的 single int 转换为 pair.

例如:

d = (a++, b+=3, c);

将:

  • a加一;
  • b加三;和
  • d 设置为 c 的任何值。

如果您想要 实际 对,您应该使用 std::make_pair(a, b) 之类的东西。在您的特定情况下,这将类似于:

return (s % g != 0) ? make_pair(-1, -1) : make_pair(g, s - g);