想要查找二进制码字中出现的 1 或 0 的位置



我做了一个程序,其中我保留了一个随机二进制码字(例如1001101(的字符串,我希望能够创建一个列表或向量,其中它告诉我 1 或 0 的位置。例如,1 的位置列表将是 {1,4,5,7}。我还想找出如何做相反的事情。例如,0 的位置列表可以是 {6,3,2}。我没有代码要显示,因为我真的无法弄清楚这一点。我在这里找不到任何真正帮助我的东西。谢谢!

您可以使用二进制和&轻松测试是否设置了特定位。

例如,要测试是否在foo中设置了位 3,您可以执行

bool is_set = foo & 0b100;

然后,如果设置了第三位,则将is_set true,否则false

将其包装在一个函数中,您可以在其中传入一个整数和您感兴趣的位号,并得到一个布尔值,说明它是否已设置,这是微不足道的。

使用这样的函数应该很容易构建所有设置和所有未设置位的列表。

如果你的码字是一个字符串,你可以a(先将其转换为整数,然后按照上面概述的方式做,或者b(只是迭代字符串并根据"0"或"1"测试每个字符,并根据结果将当前位置添加到正确的集合。

你可以做这样的事情: 链接

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
/*
 *Find all positions of the a SubString in given String
 */
void findAllOccurances(std::vector<size_t> & vec, std::string data, std::string toSearch)
{
    // Get the first occurrence
    size_t pos = data.find(toSearch);
    // Repeat till end is reached
    while( pos != std::string::npos)
    {
        // Add position to the vector
        vec.push_back(pos+1); //Added 1, we start to count positions at 1 instead of 0
        // Get the next occurrence from the current position
        pos =data.find(toSearch, pos + toSearch.size());
    }
}
int main()
{
    std::string data = "1001101";
    std::vector<size_t> vec;
    // Get All occurrences of the '1' in the vector 'vec'
    findAllOccurances(vec, data , "1");
    std::cout<<"All Index Position of '1' in given string are,"<<std::endl;
    for(size_t pos : vec)
        std::cout<<pos<<std::endl;
    std::vector<size_t> vec0;
    // Get All occurrences of the '0' in the vector 'vec0' backwards
    findAllOccurances(vec0, data , "0");
    std::cout<<"All Index Position of '0' in given string backwards are,"<<std::endl;
    std::reverse_copy(vec0.begin(), vec0.end(), std::ostream_iterator<int>(std::cout, "n"));
    return 0;
}

现场样品!

输出:

给定字符串中"1"的所有索引位置均为
1
4
5
7
给定字符串向后的所有索引位置"0"都是,

6 3
2

我认为这可能会对您有所帮助。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
    string binary_string;
    cin >> binary_string;
    vector <int> position_of_ones,position_of_zeroes;
    for(int i = 0; i < binary_string.length(); i++){
        if(binary_string[i] == '0'){
            position_of_zeroes.push_back(i+1);
        }
        else{
            position_of_ones.push_back(i+1);
        }
    }
    cout << "Position of 0s" << endl;
    for(int i = 0; i < position_of_zeroes.size(); i++){
        if(i != 0)    cout << ",";
        cout << position_of_zeroes[i];
    }
    cout << endl;
    cout << "Position of 1s" << endl;
    for(int i = 0; i < position_of_ones.size(); i++){
        if(i != 0)    cout << ",";
        cout << position_of_ones[i];
    }
    cout << endl;
 }

现在你可以使用这些向量了。

最新更新