的解决方案,我将建议是不是更有效,但看起来更好。:)
请尝试以下
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <utility>
#include <functional>
int main()
{
unsigned char charArray[] =
{
0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1
};
std::vector<std::pair<int,int> > posArray;
auto first = std::begin(charArray);
while ((first = std::find(first, std::end(charArray), 1)) != std::end(charArray))
{
auto last = std::find_if(first, std::end(charArray),
std::bind2nd(std::not_equal_to<int>(), 1));
posArray.push_back({ std::distance(charArray, first),
std::distance(charArray, last) - 1 });
first = last;
}
for (auto &p : posArray) std::cout << '[' << p.first
<< ' ' << p.second
<< ']' << std::endl;
return 0;
}
输出是
[2 4]
[6 7]
[9 9]
[13 14]
如果数组从0只包括1,那么您可以替代这种说法
auto last = std::find_if(first, std::end(charArray),
std::bind2nd(std::not_equal_to<int>(), 1));
这一个
auto last = std::find(first, std::end(charArray), 0);
在这种情况下,循环会像
while ((first = std::find(first, std::end(charArray), 1)) != std::end(charArray))
{
auto last = std::find(first, std::end(charArray), 0);
posArray.push_back({ std::distance(charArray, first),
std::distance(charArray, last) - 1 });
first = last;
}
要编写必须保留内存为载体更高效的代码。
例如
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <utility>
#include <functional>
int main()
{
unsigned char charArray[] =
{
0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1
};
std::vector<std::pair<int,int> > posArray;
size_t n = std::inner_product(std::next(std::begin(charArray)),
std::end(charArray),
std::begin(charArray),
0ul,
std::plus<size_t>(),
std::greater<char>());
n += charArray[0] == 1;
posArray.reserve(n);
auto first = std::begin(charArray);
while ((first = std::find(first, std::end(charArray), 1)) != std::end(charArray))
{
auto last = std::find(first, std::end(charArray), 0);
posArray.push_back({ std::distance(charArray, first),
std::distance(charArray, last) - 1 });
first = last;
}
for (auto &p : posArray) std::cout << '[' << p.first
<< ' ' << p.second
<< ']' << std::endl;
return 0;
}
如果成功,那么这将是更好? – 2014-09-26 13:37:28
换句话说,你将不得不告诉我们什么是“更好”是指给你,或者你只是得到基于什么别人的“更好”的解释一堆输入的是基于自己的偏见。 – 2014-09-26 13:38:31
可能是['标准:: bitset'(http://en.cppreference.com/w/cpp/utility/bitset)会更适合来处理这个,但仰视的位置可能不会发生很大的变化。 – 2014-09-26 13:40:28