gpt4 book ai didi

c++ - 如何将整数字符串转换为二维整数 vector ?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:56 26 4
gpt4 key购买 nike

假设我想要的输出是方形输出(它们之间不需要任何空格):

1234
2345
3456
4567

给定相同的数字平方,但每个数字都是 std::string,我如何实现一个 2D vector 每个正方形的字符,然后首先将每个字符转换为 int,然后存储到行和列的二维 vector 中以生成完全相同的正方形?

我知道二维 vector 需要是

vector<vector<int>> square_vector;

但是我在获取所有成对的行和列时遇到了问题。

编辑:如果我的方 block 是

1234
2345
3456
4567

我想先遍历第一行1234。然后在该行中,我想遍历每一列字符 1, 2, 3, 4 并将每个字符转换为 int。转换后,我想将 push_back 作为一行放入 2D vector 中。一行完成后,我想转到下一行并执行相同的任务。

最佳答案

But I was having trouble taking all of the paired rows and column.

当您使用 std::vector 时,为什么不简单地使用 range based for loop 来完成这项工作。希望评论能帮助您完成代码。

#include <iostream>
#include <vector>
#include <string>

int main()
{
// vector of strings to be converted
std::vector<std::string> strVec{ "1234", "2345", "3456", "4567" };
// get the squre size
const std::size_t size = strVec[0].size();
// resulting 2D vector
std::vector<std::vector<int>> result; result.reserve(size);

for (const std::string& strInteger : strVec)
{
std::vector<int> rawVec; rawVec.reserve(size);
for (const char Char : strInteger)
// if (std::isdigit(Char)) //(optional check)
rawVec.emplace_back(static_cast<int>(Char - '0'));
// save the row to the 2D vector
result.emplace_back(rawVec);
}
// print them
for (const std::vector<int>& eachRaw : result)
{
for (const int Integer : eachRaw)
std::cout << Integer << " ";
std::cout << std::endl;
}
}

输出:

1 2 3 4 
2 3 4 5
3 4 5 6
4 5 6 7

关于c++ - 如何将整数字符串转换为二维整数 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52816668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com