2014-05-16 27 views
0

我有一個關鍵字矢量,我需要遍歷它。無需開始和結束遍歷矢量

我嘗試:

bool isKeyword(string s) 
{ 
    return find(keywords, keywords + 10, s) != keywords + 10; 
} 

但是這個工程的一個數組而不是一個向量。我怎樣才能改變+10來遍歷矢量?我需要這個,因爲我沒有C++ 11支持,因此我無法使用end和begin。 end()這樣

error: no matching function for call to 'find(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >::size_type, std::string&)'| 
+5

'keywords.begin()'。你不需要C++ 11。爲什麼+10,但? – dlf

+0

@dlf,據推測目前的數組有10個元素。無論如何,如果你沒有C++ 11,你可以很容易地創建自己的'begin'和'end'版本。 – chris

+0

看看這個關於vector的優秀參考:[std :: vector](http://en.cppreference.com/w/cpp/container/vector)。在C++ 11發佈之前,你會發現'begin()'和'end()'以及相應的迭代器已經被支持了。 –

回答

2

使用begin()和:上面的代碼給出

錯誤

find(keywords.begin(), keywords.end(), s) 

下面是一個例子:

#include <iostream> 
#include <vector> 
#include <string> 
#include <algorithm> // std::find 

using namespace std; 

bool isKeyword(string& s, std::vector<string>& keywords) 
{ 
    return (find(keywords.begin(), keywords.end(), s) != keywords.end()); 
} 

int main() 
{ 
    vector<string> v; 
    string s = "Stackoverflow"; 
    v.push_back(s); 
    if(isKeyword(s, v)) 
     cout << "found\n"; 
    else 
     cout << "not found\n"; 
    return 0; 
} 

正如其他國家,你這樣做這個應用程序不需要C++11

Ref std::find

+0

爲什麼在不需要拷貝時通過'string s'值? –

+0

我只是複製粘貼OP的原型。好的一點,我會編輯@ C.R。 – gsamaras

+1

進一步挑剔,引用應該是'const',否則你將無法將臨時對象傳遞給它。 –