我正在尝试编写一个程序,该程序从输入文件中获取行,将这些行排序为“签名”,以便将所有相互变位的单词组合在一起。我必须使用映射,将“签名”存储为键,并将与这些签名匹配的所有单词存储到字符串向量中。之后,我必须在同一行上打印所有相互变位的单词。这是我到目前为止所拥有的:
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;
string signature(const string&);
void printMap(const map<string, vector<string>>&);
int main(){
string w1,sig1;
vector<string> data;
map<string, vector<string>> anagrams;
map<string, vector<string>>::iterator it;
ifstream myfile;
myfile.open("words.txt");
while(getline(myfile, w1))
{
sig1=signature(w1);
anagrams[sig1]=data.push_back(w1); //to my understanding this should always work,
} //either by inserting a new element/key or
//by pushing back the new word into the vector<string> data
//variable at index sig1, being told that the assignment operator
//cannot be used in this way with these data types
myfile.close();
printMap(anagrams);
return 0;
}
string signature(const string& w)
{
string sig;
sig=sort(w.begin(), w.end());
return sig;
}
void printMap(const map& m)
{
for(string s : m)
{
for(int i=0;i<m->second.size();i++)
cout << m->second.at();
cout << endl;
}
}
第一个解释有效,没想到这么简单!但是现在我的打印功能给了我:
prob2.cc: In function âvoid printMap(const std::map<std::basic_string<char>, std::vector<std::basic_string<char> > >&)â:
prob2.cc:43:36: error: cannot bind âstd::basic_ostream<char>::__ostream_type {aka std::basic_ostream<char>}â lvalue to âstd::basic_ostream<char>&&â
In file included from /opt/centos/devtoolset-1.1/root/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/iostream:40:0,
尝试了很多变化,他们总是抱怨装订
void printMap(const map<string, vector<string>> &mymap)
{
for(auto &c : mymap)
cout << c.first << endl << c.second << endl;
}