我需要帮助审查我的代码片段复制如下。下面的代码计算给定大小为11的数组中的连续数组数。
#define size 11
#define ONE 1
using namespace std;
#include <iostream>
#include "stdio.h"
int arr[11] = {1, 0, 1, -1, 0, 0, 1, 1,0, 1, 1};
int sequence_count = 0;
int loop_count;
bool continuity = true;
for(loop_count = 0; loop_count<size; loop_count++)
{
if((arr[loop_count]&ONE) == ONE)
{
if(continuity)
sequence_count++;
else
{
continuity = true;
sequence_count++;
}
}
else
{
continuity = false;
sequence_count = 0;
}
}
cout << sequence_count << endl;发布于 2016-05-16 13:16:54
您从不使用此包含的标题中的任何内容:
#include "stdio.h"此外,在C++中,如果可用的话,您应该包括C头的C++前端:
#include <cstdio>C++中数组索引的自然类型是std::size_t (或简单地说是C中的size_t ),因为它涵盖了当前体系结构中所有可能的索引值。
size_t loop_count;通过扩展,您需要相同的类型来计算最长序列的长度。
size_t sequence_count = 0;我不认为ONE作为宏的声明非常有用。如果您希望算法处理任意数字的序列,则应该将其包装在一个函数中,并将该数字作为函数参数提供。
size_t longest_sequence( const int *array, size_t array_length, int n )
{
// ...
return sequence_count;
}您的代码片段返回最后的奇数序列的长度-而不是最长的序列!让我们看看如何修复它(包括前面提到的改进):
#include <algorithm>
#include <iostream>
std::size_t longest_sequence( const int *array, std::size_t array_size, int n )
{
std::size_t longest_sequence_length = 0,
current_sequence_length = 0;
for( std::size_t i = 0; i < array_size; i++)
{
if (array[i] == n)
{
current_sequence_length++;
}
else
{
if (current_sequence_length > longest_sequence_length)
longest_sequence_length = current_sequence_length;
current_sequence_length = 0;
}
}
return std::max(current_sequence_length, longest_sequence_length);
}
int main()
{
static const int arr[] = { 1, 0, 1, -1, 0, 0, 1, 1, 1, 0, 1, 1 };
std::cout << longest_sequence(arr, sizeof(arr) / sizeof(*arr), 1) << std::endl;
}由于这是C++,所以可以使用函数模板来概括该算法,以处理任意容器/迭代器和元素类型:
#include <algorithm>
#include <array>
#include <iostream>
template <class Iterator, class T>
std::size_t longest_sequence( Iterator begin, Iterator end, T n )
{
std::size_t longest_sequence_length = 0,
current_sequence_length = 0;
for( ; begin != end; ++begin)
{
if (*begin == n)
{
current_sequence_length++;
}
else
{
if (current_sequence_length > longest_sequence_length)
longest_sequence_length = current_sequence_length;
current_sequence_length = 0;
}
}
return std::max(current_sequence_length, longest_sequence_length);
}
int main()
{
static const std::array<int, 12> arr2 = { 1, 0, 1, -1, 0, 0, 1, 1, 1, 0, 1, 1 };
std::cout << longest_sequence(arr2.begin(), arr2.end(), 1) << std::endl;
}https://codereview.stackexchange.com/questions/128475
复制相似问题