我们可以通过调用标准库来替换循环来计算整数集合中的前导零吗?
我正在学习std,但由于我需要知道前一个元素,所以无法想办法使用count或count_if之类的东西.
int collection[] = { 0,0,0,0,6,3,1,3,5,0,0 };
auto collectionSize = sizeof(collection) / sizeof(collection[0]);
auto countLeadingZeros = 0;
for (auto idx = 0; idx < collectionSize; idx++)
{
if (collection[idx] == 0)
countLeadingZeros++;
else
break;
}
// leading zeros: 4*0
cout << "leading zeros: " << countLeadingZeros << "*0" << endl;
Run Code Online (Sandbox Code Playgroud)
我有一个类似的案例来统计同一个集合中的尾随零.
auto countTrailingZeros = 0;
for (auto idx = collectionSize - 1; idx >= 0; idx--)
{
if (collection[idx] == 0)
countTrailingZeros++;
else
break;
}
// trailing zeros: 2*0
cout << "trailing zeros: " << countTrailingZeros << "*0" << endl;
Run Code Online (Sandbox Code Playgroud)
下面是一个完整的构建示例.
#include <iostream>
using namespace std;
int main()
{
int collection[] = { 0,0,0,0,6,3,1,3,5,0,0 };
auto collectionSize = sizeof(collection) / sizeof(collection[0]);
auto countLeadingZeros = 0;
for (auto idx = 0; idx < collectionSize; idx++)
{
if (collection[idx] == 0)
countLeadingZeros++;
else
break;
}
cout << "leading zeros: " << countLeadingZeros << "*0" << endl;
auto countTrailingZeros = 0;
for (auto idx = collectionSize - 1; idx >= 0; idx--)
{
if (collection[idx] == 0)
countTrailingZeros++;
else
break;
}
cout << "trailing zeros: " << countTrailingZeros << "*0" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
一种方法是使用std::find_if.
auto countLeadingZeros = std::find_if(
std::begin(collection), std::end(collection),
[](int x) { return x != 0; }) - std::begin(collection);
auto countTrailingZeros = std::find_if(
std::rbegin(collection), std::rend(collection),
[](int x) { return x != 0; }) - std::rbegin(collection);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
288 次 |
| 最近记录: |