2013-04-02 30 views
0

上下文: 我在< -string,vector-> map上執行一個std :: find與std :: string。然後它返回一個向量的迭代器,我將返回的迭代器保存在一個常量迭代器中。在返回的迭代器中搜索向量

問題: 我現在想通過返回的常量迭代器遍歷和索引爲0的字符串比較每個向量所以像:

​​

這種方法只對我蠻好,我想知道如果有更優雅的做法,我錯過了什麼?

感謝您的幫助,這=]

+0

如果它的工作原理,它的精細與你我沒有看到這個問題。對我來說也很好。 – john

+0

是的它的工作原理,但我想知道是否有任何stl魔術我可以使用,使其更好。 – OriginalCliche

+0

我不這麼認爲,但無論如何,爲什麼STL魔術會讓它變得更好?如果你的意思是我認爲你的意思是STL魔術,那麼它已經結束了。我的意思是你可以使用std :: find_if(或其他),但爲什麼要麻煩。只是讓代碼更復雜,不太容易理解(當然這是個人意見)。 – john

回答

-2

有一個非常貧窮的方式,我可以想像的。這不是普通的,應該(甚至必須)永遠不會被使用。爲矢量覆蓋比較運算符,因此它只比較0個位置。然後使用map :: find()方法。好玩。

2

而不是明確地編碼的搜索,你可以使用std::find_if():在http://ideone.com/nkI7fk

std::vector<std::vector<std::string>> vstring 
    { 
     { "no", "yes" }, 
     { "help", "yes" }, 
     { "true", "false" } 
    }; 

const std::string myStr = "help"; 
auto f = std::find_if(vstring.begin(), vstring.end(), 
      [&](std::vector<std::string>const & vs) 
      { 
       return !vs.empty() && myStr == vs[0]; 
      }); 


if (f != vstring.end()) 
{ 
    // Found. 
} 

觀看演示。

0

的一種方式,以使這更「優雅」是這樣的:

// C++11 allows `using` to be used instead of `typedef` 
using map_type = std::map<std::string, std::vector<some_type>>; 

// First find the starting point of our secondary search 
const auto itr = map.find(some_string); 

// Do secondary search 
const auto found = std::find_if(itr, map.end(), 
           [](const map_type::value_type& pair) 
           { 
            return (!pair.second.empty() && 
              pair.second[0] == myStr); 
           }); 
if (found != map.end()) 
{ 
    // Found the item 
} 
+0

我錯過了什麼,爲什麼你從找到的元素搜索到地圖的盡頭? – David

+0

@Dave那麼這就是OP似乎在做什麼。 –