2017-09-24 48 views
-1

我是C++的新手。当我尝试输出字符串向量的结果时出现错误。我希望有人能为什么? GenerateCombinations函数的代码是https://www.programmingalgorithms.com/algorithm/unique-combinations。我写了main()函数。我使用VS 2015年社区C++操作符不匹配操作数错误

#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; 

} 
+0

欢迎来到堆栈溢出。你期望什么结果,你会得到什么结果? – Beta

+2

'组合'显然是一个'矢量<矢量>'。因此,它的'begin()'显然是一个'vector > :: iterator',但是你试图将它分配给一个'vector :: iterator'。这是行不通的。 –

+0

感谢Sam的快速响应。我是你所建议的变化,但仍然得到一个错误<< line – gearhead

回答

0

由于@Sam has pointed out in the comments,你正试图从combinations.begin()分配std::vector<std::vector<std::string>>::iteratorstd::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"; 
} 
+0

考虑使用'auto&',除非你需要一个副本 – vu1p3n0x

相关问题