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

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

std::vector<std::vector<std::string>> getCombinations(const std::vector<std::string>& strings) {
    std::vector<std::vector<std::string>> combinations;
    int n = strings.size();
    
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            std::vector<std::string> combination;
            combination.push_back(strings[i]);
            combination.push_back(strings[j]);
            combinations.push_back(combination);
        }
    }
    
    return combinations;
}

void printMatrix(const std::vector<std::vector<std::string>>& matrix) {
    for (const auto& row : matrix) {
        for (const auto& element : row) {
            std::cout << element << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector<std::string> strings = {"string1", "string2", "string3", "string4"};
    std::vector<std::vector<std::string>> combinations = getCombinations(strings);
    
    printMatrix(combinations);
    
    return 0;
}

输出结果为:

string1 string2 
string1 string3 
string1 string4 
string2 string3 
string2 string4 
string3 string4 

在这个示例中,我们首先定义了一个getCombinations函数,该函数接受一个字符串向量作为输入,并返回一个保存两两组合的字符串向量的向量。然后,我们定义了一个printMatrix函数,用于打印保存组合结果的矩阵。在main函数中,我们定义了一个字符串向量strings,并将其作为输入传递给getCombinations函数来获取组合结果。最后,我们调用printMatrix函数来打印组合结果矩阵。

c++实现多个字符串之间的两两组合并保存为一个矩阵

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

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