vector.size() 返回 1,即使其中有超过 1 个元素
vector.size() returns 1 even though there are more than 1 elements in it?
所以我是C++向量的新手,我的目标是从文件中读取一行,将其存储在字符串向量中,将其转换为整数并将其推送到 int 向量。我遇到了一个问题,当我将 char 转换为 int 时,我会丢失前导 0。我想保留前导 0(该文件是矩阵文件(。我将最终文件存储在 2D int 矢量中。当我运行 temp.size(( 时,我得到的结果为 1,我知道这与我将字符串转换为整数的方式有关,所以我相信向量中只存储了 1 个数字。
std::vector< std::vector<int> > data;
std::vector< std::vector<int> > res;
std::ifstream f("input.txt", ios::binary);
string line;
int count;
while(std::getline(f,line))
{
std::vector<string> line_data;
std::vector<int> temp;
std::istringstream iss(line);
std::string value;
while(iss >> value)
{
line_data.push_back(value);
std::transform(line_data.begin(), line_data.end(),
std::back_inserter(temp),
[](std::string &s) { return std::stoi(s); } );
count = value.length();
count = count - temp.size(); // temp.size() returns 1, why is that and how can I fix it?
cout << count <<endl;
temp.insert(temp.begin(),count,0);
data.push_back(temp);
}
我的输入是一个未知长度的布尔方阵。 例如:
00101
10101
10100
00101
01111
编辑:
从 int 向量数据获取输出时:
101
10101
10100
101
1111
失去前导0
所以我尝试计算值和温度长度的差异并手动插入 0。
为什么要对文本数据使用二进制模式?稍微简化了一下,所以它来了:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
int main()
{
std::ifstream f("input.txt");
std::vector< std::vector<int> > data;
std::string line;
// fill data
while (std::getline(f, line))
{
std::vector<int> temp;
std::transform(line.begin(), line.end(),
std::back_inserter(temp),
[](char c) { return std::stoi(std::string(&c, 1)); });
data.push_back(temp);
}
// print data
for (std::vector<int> x : data)
{
for (int y : x)
std::cout << y;
std::cout << std::endl;
}
return 0;
}
指纹:
00101
10101
10100
00101
01111
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- "Safe"将元素添加到 std::vector 的方法,超出了其 size() 但低于其容量 ()
- 为什么 size() 在与其他堆栈交换元素后提供错误的堆栈大小?
- vector.size() 返回 1,即使其中有超过 1 个元素
- 我可以使用 std::vector.size() 来控制删除元素的循环吗?
- std::vector size()-1 ALWAYS给出最后一个元素的索引吗?
- c++ set size不对应于它的元素个数
- C++在.size()之后丢失向量元素