【发布时间】:2019-06-18 17:42:58
【问题描述】:
我正在 Edabit 上尝试挑战,当前的挑战是关于嵌套向量。说明是: 如果第一个数组可以嵌套在第二个数组中,则创建一个返回 true 的函数。
如果满足以下条件,数组 1 可以嵌套在数组 2 中:
- 阵列 1 的最小值 > 阵列 2 的最小值
- 阵列 1 的最大值
例子:
canNest([1, 2, 3, 4], [0, 6]) ➞ true
canNest([3, 1], [4, 0]) ➞ true
canNest([9, 9, 8], [8, 9]) ➞ false
canNest([1, 2, 3, 4], [2, 3]) ➞ false
我编写的未通过所有测试的代码如下:
bool canNest(std::vector<int> arr1, std::vector<int> arr2) {
return (std::min_element(arr1.begin(), arr1.end()) >
std::min_element(arr2.begin(), arr2.end()) &&
std::max_element(arr1.begin(), arr1.end()) <
std::max_element(arr2.begin(), arr2.end()));
}
此代码使 test3、test4 和 test5 通过,但不通过 test1 和 test2。
It(test1){Assert::That(canNest({1, 2, 3, 4}, {0, 6}), Equals(true));}
It(test2){Assert::That(canNest({3, 1}, {4, 0}), Equals(true));}
It(test3){Assert::That(canNest({9, 9, 8}, {8, 9, 10}), Equals(false));}
It(test4){Assert::That(canNest({9, 9, 8}, {8, 9}), Equals(false));}
It(test5){Assert::That(canNest({1, 2, 3, 4}, {2, 3}), Equals(false));}
编辑:挑战可以在here 找到,用于测试解决方案!
【问题讨论】:
-
我记得,你必须用*取消引用 min_element 和 max_element:cplusplus.com/reference/algorithm/min_element
-
来到这样的论坛,是在寻求其他人帮助您解决问题,却缺少挑战的精神吗?
-
min/max_element 返回一个迭代器,尊重它们
-
如
std::min_element和std::max_element的文档中所述,它们返回迭代器,而not 元素。 -
请注意,使用
std::minmax_element您可以做得更好。
标签: c++ arrays vector containers c++17