的解決方案,我將建議是不是更有效,但看起來更好。:)
請嘗試以下
#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