我是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;
}
答案 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)
此处combination
是std::vector<std::string>
,因此您无法打印它,您还需要遍历它:
for (auto combination : combinations)
{
for (auto c : combination)
{
std::cout << c << ' ';
}
std::cout << "\n";
}