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

标签 c++ algorithm c++11 stdvector stdstring

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

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/

相关文章:

c++ - 如何在 Veins 4.4 中正确使用 "moduleDisplayString"?

c++ - 如何使用标准库迭代相等的值?

c++ - "T const&t = C().a;"是否会延长 "a"的生命周期?

c++ - 访问 POD 结构数组作为其单个成员的数组是否违反严格别名?

c++ - 将 map 与 vector 和缓存影响结合使用

c++ - cuFFT 流的并发

c++ - boost::asio::io_context::run_one_for() 无法发送大缓冲区

c++ - 无法将元素插入到包含引用的类的 vector 中

algorithm - 如何修改我的 Akka 流 Prime 筛子以排除对已知素数的模检查?

arrays - 使用递归分离整数数组中的偶数和奇数