以下是一个用 C++ 实现多个字符串之间两两组合并保存为一个矩阵的示例代码:

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

std::vector<std::vector<std::string>> createCombinationMatrix(const std::vector<std::string>& strings) {
    std::vector<std::vector<std::string>> matrix;
    int n = strings.size();

    for (int i = 0; i < n; i++) {
        std::vector<std::string> row;
        for (int j = 0; j < n; j++) {
            std::string combination = strings[i] + strings[j];
            row.push_back(combination);
        }
        matrix.push_back(row);
    }

    return matrix;
}

int main() {
    std::vector<std::string> strings = {'abc', 'def', 'ghi'};
    std::vector<std::vector<std::string>> matrix = createCombinationMatrix(strings);

    for (const auto& row : matrix) {
        for (const auto& element : row) {
            std::cout << element << ' '; 
        }
        std::cout << std::endl;
    }

    return 0;
}

该示例中,我们定义了一个函数 createCombinationMatrix,它接受一个字符串向量作为输入,并返回一个包含两两组合的矩阵。在 main 函数中,我们创建了一个包含三个字符串的向量,并调用 createCombinationMatrix 函数生成矩阵。然后,我们使用嵌套的循环遍历矩阵并打印出每个元素。

运行该程序,输出结果为:

abcabc abcdef abcghi
defabc defdef defghi
ghiabc ghidef ghighi

这是一个 3x3 的矩阵,每个元素是两个字符串的组合。

C++ 实现字符串两两组合并生成矩阵

原文地址: https://www.cveoy.top/t/topic/fwcQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录