C++ 运算符不匹配操作数错误

c++ operator doesn't match operand error

本文关键字:错误 操作数 不匹配 运算符 C++      更新时间:2023-10-16

我是C 的新手。当我尝试输出字符串向量的结果时,我会遇到错误。我希望有人可以吗?GenerateCombinations功能的代码来自https://www.programmingalgorithms.com/algorithm/nique-combinations。我写了主()函数。我正在使用vs社区2015。

#include "stdafx.h"
#include <iostream>
#include <Vector>
#include <string>
using namespace std;

//*****Please include following header files***** /
// string
// vector
/***********************************************/
/*****Please use following namespaces*****/
// std
/*****************************************/
static vector<vector<string>> GenerateCombinations(vector<string> arr)
{
    vector<vector<string>> combinations;
    int length = arr.size();
    for (int i = 0; i < (1 << length); ++i)
    {
        vector<string> combination;
        int count = 0;
        for (count = 0; count < length; ++count)
        {
            if ((i & 1 << count) > 0)
                combination.push_back(arr[count]);
        }
        if (count > 0 && combination.size() > 0) {
            combinations.push_back(combination);
        }
    }
    return combinations;
}

int main() {
    vector<string> arr = { "How", "Are", "You" };
    vector<vector<string>> combinations = GenerateCombinations(arr);
    vector <string> ::iterator itr;
    for (itr = combinations.begin(); itr < combinations.end(); itr++)
    {
        cout << *itr << endl;
}

正如@SAM在评论中指出的那样,您正在尝试将std::vector<std::vector<std::string>>::iteratorcombinations.begin()分配到std::vector<std::string>::iterator,因此是不匹配的。

解决问题的最简单方法是不必担心实际类型,然后使用auto

for (auto itr = combinations.begin(); itr < combinations.end(); ++itr)

或更简单:

for (auto combination : combinations)

在这里combinationstd::vector<std::string>,因此您不能仅仅打印,您也需要迭代:

for (auto combination : combinations)
{
    for (auto c : combination)
    {
        std::cout << c << ' ';
    }
    std::cout << "n";
}
相关文章: