C ++有没有办法将矢量调整为特定字符?

时间:2017-02-01 00:35:20

标签: c++ vector

基本上我有一个包含二进制位的向量,我想将向量的大小调整为有用信息的长度。 Vector的长度非常大,因为它保持用户输入,而且我找不到一种方法来使向量的长度动态变为用户输入的长度。

所以矢量内容基本上是〜 1001101010100110010110100000000000000000000000000000000

有没有办法将矢量缩小为: 10011010101001100101101

myVector.shrink_to_fit();

无法解决我的问题,因为向量填充了空数据。

//Included Libraries
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>


using namespace std;

                             // Var Declerations
string inputText;
std::vector<int> ba; //ba=binary array* originally was an array


void displayBinaryVector()
{
    for (int i = 0; i < ba.size(); i=i+8)
    {
        cout << ba.at(i) << ba.at(i+1) << ba.at(i+2) << ba.at(i+3) << ba.at(i+4) << ba.at(i+5) << ba.at(i+6) << ba.at(i+7) << endl;
    }
}

//Main Function
int main()
{

    // Gets input
    cout << "Please Enter What You Would Like To Be Encoded" << endl;
    getline(cin, inputText);
    ba.resize((128*8));
    convertToBinary();
    displayBinaryVector();
    return 0;
}

**编辑**澄清的代码(我认为)并更新到我当前的解决方案。

我认为我找到了适合我特定情况的解决方案:

void displayBinaryVector()
{
for (int i = 0; i < ba.size();)
{
    cout << ba.at(i) << ba.at(i+1) << ba.at(i+2) << ba.at(i+3) << ba.at(i+4)     << ba.at(i+5) << ba.at(i+6) << ba.at(i+7) << endl;
    i = i + 8;
    if ((ba.at(i) + ba.at(i + 1) + ba.at(i + 2) + ba.at(i + 3) + ba.at(i +   4) + ba.at(i + 5) + ba.at(i + 6) + ba.at(i + 7)) == 0)
    {
        ba.resize(i);
    }
}
}

我仍然很好奇是否有一个方法或预先编写的函数,你可以调用它基本上会反转向量搜索,直到找到指定的值/值并删除任何已经“检查”的元素。

1 个答案:

答案 0 :(得分:0)

以下内容从PyEnchant中移除了最右侧的零序列(也适用于{0}值的vector<bool>):

vector<int>

使用后向迭代器,我们#include <algorithm> vector<bool> ba {0,1,1,0,0,1,0,1,0,1,1,0,0,0}; ba.resize(ba.rend() - std::find(ba.rbegin(), ba.rend(), 1)); 从最右边出现find。然后将矢量调整大小到开始位置和此找到位置之间的间隙。该解决方案是健壮的,适用于空向量和具有纯零或一的向量的特殊情况。

相关问题