How to convert a character (flatten) matrix to a single string in C++

4 Answers

0 votes
#include <iostream>
#include <vector>
#include <string>
 
std::string flattenMatrix(const std::vector<std::vector<char>>& mat) {
    std::string result;

    // Append all characters row by row
    for (const auto& row : mat) {
        result.append(row.begin(), row.end());
    }
 
    return result;
}
 
int main() {
    std::vector<std::vector<char>> matrix = {
        {'H','e','l','l','o'},
        {' ','W','o','r','l','d'},
        {'!'}
    };
 
    std::string output = flattenMatrix(matrix);
 
    std::cout << "Flattened string: " << output << std::endl;
}

 
 
/*
run:
 
Flattened string: Hello World!
 
*/

 



answered Jan 10 by avibootz
edited Jan 10 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <string>

std::string flattenMatrix(const std::vector<std::vector<char>>& mat) {
    std::string result; 
    
    for (auto& row : mat) 
        result.insert(result.end(), row.begin(), row.end());

    return result;
}

int main() {
    std::vector<std::vector<char>> matrix = {
        {'H','e','l','l','o'},
        {' ','W','o','r','l','d'},
        {'!'}
    };

    std::string output = flattenMatrix(matrix);

    std::cout << "Flattened string: " << output << std::endl;
}



/*
run:

Flattened string: Hello World!

*/

 



answered Jan 10 by avibootz
0 votes
#include <iostream>
#include <string>
 
#define ROWS 2
#define COLS 6
 
std::string flattenMatrix(char arr[][6], int R, int C) {
    std::string result;

    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            result.push_back(arr[i][j]);
 
    return result;
}
 
int main() {
    char matrix[][COLS] = {
        {'H','e','l','l','o',' '},
        {'W','o','r','l','d','!'}
    };
 
    std::string output = flattenMatrix(matrix, ROWS, COLS);
 
    std::cout << "Flattened string: " << output << std::endl;
}
 
 
 
/*
run:
 
Flattened string: Hello World!
 
*/

 



answered Jan 10 by avibootz
edited Jan 10 by avibootz
0 votes
#include <iostream>
#include <string>

#define ROWS 2
#define COLS 6

int main() {
    char *matrix = new char[ROWS * COLS]{
        'H','e','l','l','o',' ',
        'W','o','r','l','d','!'
    };

    std::string output(matrix, matrix + ROWS * COLS);

    delete[] matrix;

    std::cout << "Flattened string: " << output << std::endl;
}



/*
run:

Flattened string: Hello World!

*/

 



answered Jan 10 by avibootz

Related questions

...