假设我有一个
std:array<int>
,例如:
0 1 1 1 0 1 1 0
我想使用 std(如果可能)在 c++11 中执行此操作:
因此得到上面示例的结果:
1 3 1 2 1
谢谢
您可以通过一次输入值来应用此逻辑,同时创建结果向量:
至于
std::array
:由于这是一个固定大小的数据类型,并且结果的大小事先未知,所以我会使用向量代替。但我添加了将数组转换为向量的代码。如果您的要求不坚持 array
,您当然可以从一开始就用 std::vector
表示您的输入:
#include <iostream>
#include <array>
#include <vector>
std::vector<int> convert(std::vector<int> bin) {
std::vector<int> v;
int prevBit = 0;
for (auto bit : bin) {
if (bit & prevBit) {
v.back()++;
} else {
v.push_back(1);
}
prevBit = bit;
}
return v;
}
// Example run:
int main() {
std::array<int, 8> arr = {0, 1, 1, 1, 0, 1, 1, 0};
// Convert array to vector
std::vector<int> vec(std::begin(arr), std::end(arr));
// Apply conversion
std::vector<int> result = convert(vec);
// Output the result
for (auto val : result) {
std::cout << val << " ";
}
std::cout << std::endl;
}