2013-02-20 49 views
0

我正在嘗試創建計算機的定價系統,並且我想創建兩個向量,一個存儲項目名稱,另一個爲該項目的價格。我的計劃是有兩個方法,「find_item」,它在向量中查找項目名稱並返回其索引,以及「get_itemPrice」,它從find_item獲取索引並獲取價格。我的問題是提出一個代碼,它將一個字符串對象放入向量中並返回其索引位置。C++:在向量中搜索

+3

嘗試使用'std :: map'而不是'vector'。搜索地圖密鑰沒有問題 – triclosan 2013-02-20 21:18:44

+0

也許你可以澄清一下:A)什麼是「字符串矢量」?一串字符串? B)你在哪裏搜索它?在另一個結構?有了更多的細節,人們將能夠提供更好的答案。 – juanchopanza 2013-02-20 21:23:16

+0

我很抱歉,當我輸入時,我很匆忙。請參閱編輯的消息^。 – Wormhole99 2013-02-20 23:34:31

回答

6

您可以簡單地使用std::find。它會將迭代器返回到第一個元素,該元素等於您正在搜索的元素,如果沒有找到,則返回end()。然後,您可以使用std::distance獲得該索引,如果您真的需要,則可以使用

+1

爲什麼?海報問了一下載體 – 2013-02-20 21:18:04

+0

這是一個2步法,對不對? – Dukeling 2013-02-20 21:18:13

+1

@Dukeling std :: distance對於矢量來說是恆定的時間和快速的,所以它的影響可以忽略不計。 – juanchopanza 2013-02-20 21:20:12

0

像這樣:

vector<int> vect; 
int i = 0; 
for (vector<int>::iterator iter = vect.begin(); iter != vect.end(); ++iter) 
{ 
    if (*iter == vect) 
    break; 
    i++; 
} 
if (i == vect.size()) 
    // not found 
else 
    // i is your index 
0

,如果你真的想使一個算法像這樣做,但一般不應該嘗試擊敗那些在STL看到算法頭

unsigned find_str(const vector<string>& vec, const string& key){ 
    unsigned count = 0; 
    vector<string>::const_iterator it; 
    for (it = vec.begin() ; it < vec.end(); it++){ 
     if(*it == key) 
      return count; 
     count++; 
    } 
    /*throw not found error here.*/ 
}