简体   繁体   中英

What is the best way to convert a 2D string vector to a 2D int vector c++?

I am reading a matrix from a file, I am reading it into a string vector so I can preserve the leading 0s in the file. Now I want to apply some mathematical operations on the vector and so I want to copy it into a 2D int vector. I am new to using vectors and I saw there was a couple of examples for 1D vectors, but I am confused with 2D vectors.

std::vector< std::vector<string> > data;
std::vector< std::vector<int> > res;
std::ifstream f("input.txt", ios::binary);
std::string line;

while(std::getline(f,line))
{
  std::vector<string> line_data;
  std::istringstream iss(line);
  std::string value;
  while(iss >> value)
    {   
        line_data.push_back(value);
}
  data.push_back(line_data);
}

My code above read the file line by line as a string and wrote it to the 2D string vector named data. My goal is to copy 2D data vector to the 2D res vector, how do I proceed with that ?

input.txt is a square boolean matrix. for instance

0101
1010
1100
0001

edit:

As recommended I tried using the transform function and this is where I got to :

for (unsigned int i = 0; i < data.size(); ++i)
{   std::vector<int> temp_data;

    std::transform(data[i].begin(), data[i].end(),
            std::back_inserter(temp_data),
            [](const auto& element) {   return std::stoi(element); });
    res.push_back(temp_data);
}

but I am getting an invalid use of auto error here, and I am not even sure this is right for 2D vectors.

A simple solution is to use std::transform with a lambda that calls std::stoi .

Here's an example:

#include <string>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::string> vs = {"123", "456", "789"};
    std::vector<int> vi;
    std::transform(vs.begin(), vs.end(),
        std:back_inserter(vi),
        [](const auto& element) { return std::stoi(element); });
// 'vi' now contains the integers 123, 456, 789
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM