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

时间:2017-09-24 23:23:59

标签: c++

我是c ++的新手。我尝试输出字符串向量的结果时收到错误。我希望有人可以为什么? GenerateCombinations函数的代码来自https://www.programmingalgorithms.com/algorithm/unique-combinations。我写了main()函数。我正在使用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;

}

1 个答案:

答案 0 :(得分:0)

作为@Sam has pointed out in the comments,您正试图从std::vector<std::vector<std::string>>::iterator分配combinations.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";
}