2010-12-17 50 views
2

我想使用C++ map函數map::find來確定某個特定的字符串是否位於地圖內。我知道發現返回map::end,但我不確定如何使用它。因此,如果在names_info_中都存在相同的字符串,我希望它將該字符串打印到屏幕上。如何在地圖中使用map :: end ::在C++中查找

在我的頭:

std::vector<std::string>names_; 
std::map<std::string, unsigned int> info_; 

在的.cpp(此代碼是錯誤的):

for(unsigned int i=0;i<names_.size();i++){ 
    std::map<std::string, unsigned int>::iterator it; 
    it = info_.find(names_[i]); 
    if info_.find(names_[i]) != info_.end() 
     std::cout << names_[i] << std::endl; 
} 

什麼我在的.cpp一小段代碼片段做錯了什麼?我知道這是迭代器的東西。

+0

除了'if'語句中缺少括號之外,什麼是錯的? – Vlad 2010-12-17 23:17:33

+0

對於布爾型存在測試,使用'map.count(item)'將會更簡單,它將返回1或0(或更多的使用multimap)。 – 2010-12-17 23:55:56

+0

@Ben'.count()'對於測試multimaps(O(n))中的存在是效率低下的。 – 2010-12-18 03:05:06

回答

3

它應該是:

for(unsigned int i=0;i<names_.size();i++){ 
    if (info_.find(names_[i]) != info_.end()) 
     std::cout << names_[i] << std::endl; 
} 
3
從別的

除了:

if info_.find(names_[i]) != info_.end() 

應該是:

if (info_.find(names_[i]) != info_.end()) 

在C++(和C)由IFS測試條件和田地必須括號括起來。

1

如果表達式,如果在其他的答案中提到括號,代碼工作封閉的明顯修復程序後。

#include <iostream> 
#include <map> 
#include <vector> 

int main() { 
    std::vector<std::string>names_; 
    std::map<std::string, unsigned int> info_; 
    names_.push_back("a"); 
    names_.push_back("b"); 
    names_.push_back("c"); 
    info_["a"] = 123; 
    info_["c"] = 123; 
    info_["d"] = 456; 
    for(unsigned int i=0;i<names_.size();i++){ 
     std::map<std::string, unsigned int>::iterator it; 
     if (info_.find(names_[i]) != info_.end()) 
      std::cout << names_[i] << std::endl; 
    } 
} 

輸出:

a 
c 

是不是你問什麼?