C++有没有一种方法可以将向量调整为特定的字符
C++ is there a way to resize a vector to specific character?
基本上,我有一个包含二进制位的向量,我想调整向量的大小,使其仅为有用信息的长度。向量的长度非常大,因为它包含用户输入,我找不到一种方法使向量的长度与用户输入的长度动态。
所以矢量的内容基本上是~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
。然后,将向量的大小调整为起始位置和找到的位置之间的间隙。该解决方案是稳健的,适用于空向量的特殊情况以及具有纯零或一的向量。
相关文章:
- 在C++中调整向量中的索引
- 将 boost::odeint 与向量类一起使用,而无需调整向量的大小
- 如何按另一个向量的方向调整一个向量?
- C++初始化列表中的向量集大小或调整大小
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- 调整向量大小并检索值,这是否正确或在任何情况下都可能导致段错误?
- 如何调整作为结构或类成员的向量的大小?
- 调整STD ::向量的大小是否可以降低其能力
- 在具有容量/调整大小的类中初始化向量
- STD ::向量如何调整其内部缓冲区大小
- 将添加的列初始化为可调整大小的 2D 向量
- C++中向量容器的大小和调整大小函数
- 如何判断 std::vector 是否调整了自身大小,以及如何解释指向向量内值的指针不再有效
- 调整OpenCV Mat向量向量的大小时出乎意料的结果
- C++有没有一种方法可以将向量调整为特定的字符
- 调整向量的大小会导致 SEG 错误
- 在c++中我应该在哪里调整向量的大小
- 如何在Eigen3中调整向量的大小
- 调整向量数组的大小
- 在不调用构造函数的情况下调整c++向量的大小