2013-11-04 117 views
0

我试图编写一个程序,它从输入文件中获取行,将行分类为'签名'以将所有彼此的字典组合起来。我必须使用地图,将'签名'作为关键字存储,并将与这些签名相匹配的所有单词存储到一个字符串向量中。之后,我必须在同一行上打印所有彼此字形的单词。这是我到目前为止:map <string,vector <string>>向量值的重新分配

#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; 
} 
+4

问题是什么? –

+0

为什么你不使用'std :: multimap'? –

+0

原问题:为什么anagrams [sig1] =数据。push_back(w1)不编译。 – user2950936

回答

1

anagrams[sig1]会返回一个vector<string>参考。而不是分配给它,你只需要push_back就可以了。

sig1 = signature(w1); 
anagrams[sig1].push_back(w1); 

当你的代码是正确的,现在写的,它试图取代的载体,而不是添加到它。例如,假设您的输入包含wassaw,并且您的signature对字符串的字母进行排序。

你想这种情况是什么:

  1. 读 “是”
  2. 排序得到 “反潜”
  3. 插入 “是” 来获得:anagrams["asw"] -> ["was"]
  4. 读 “看见”
  5. 排序得到“asw”(再次)
  6. 插入“saw”得到:anagrams["asw"] -> ["was", "saw"]

然而,在您尝试编写代码的第6步中,不是添加到现有向量中,而是使用仅包含“saw”的新向量覆盖当前向量,所以结果将只是anagrams["asw"] -> ["saw"]

至于printmap云:在地图上的项目不是std::string S,他们std::pair<std::string, std::vector<std::string>>,所以当你尝试做:

void printMap(const map& m) 
{ 
    for(string s : m) 

...这显然是行不通的。我通常会使用:

for (auto s : m) 

......这使得至少可以得到那么多的编译。做任何事情的s有用的,但是,你将需要认识到,这是一个pair,所以你必须与s.firsts.second工作(和s.first将是一个string,并且s.second将是一个std::vector<std::string>)。要打印出来,您可能需要打印s.first,然后打印一些分隔符,然后查看s.second中的项目。

+0

明白了!非常感谢你! – user2950936

相关问题