C++有没有一种方法可以将向量调整为特定的字符

C++ is there a way to resize a vector to specific character?

本文关键字:调整 向量 字符 有没有 方法 一种 C++      更新时间:2023-10-16

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

所以矢量的内容基本上是~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);
}
}
}

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

以下操作从vector<bool>中删除最右边的零序(也适用于具有0-1值的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的最右边开始出现1。然后,将向量的大小调整为起始位置和找到的位置之间的间隙。该解决方案是稳健的,适用于空向量的特殊情况以及具有纯零或一的向量。