gearhead gearhead - 27 days ago 10
C++ Question

c++ operator doesn't match operand error

I am new to c++. I am getting an error when I try to output the result of a string vector. I was hoping someone can why? the code for GenerateCombinations function is from https://www.programmingalgorithms.com/algorithm/unique-combinations. I wrote the main() function. I am using VS community 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;

}

Tas Tas
Answer Source

As @Sam has pointed out in the comments, you are attempting to assign a std::vector<std::vector<std::string>>::iterator from combinations.begin() to std::vector<std::string>::iterator, hence the mismatch.

The easiest way to solve your problem is to worry less about actual types, and use auto:

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

Or more simply:

for (auto combination : combinations)

Here combination is a std::vector<std::string>, so you can't just print that, you need to iterate through that as well:

for (auto combination : combinations)
{
    for (auto c : combination)
    {
        std::cout << c << ' ';
    }
    std::cout << "\n";
}