2016-10-25 29 views
1

我正在嘗試使用向量,因爲我剛開始學習,但被卡在這個錯誤。我試圖看看cpp的參考,並寫在它上面,但仍然出現錯誤。編譯器錯誤:找不到匹配的函數

#include<vector> 
#include<iostream> 
#include<cstring> 
using namespace std; 
int main() 
{ 

vector<string> vec; 

vec.push_back("First"); 

vec.push_back("second"); 

for(int i = 0; i < 4 ; i++) 
    vec.push_back("RepeatTimes"); 

vector<string>::iterator fp = find(vec.begin(), vec.end(), "First"); 


for(vector<string>::iterator it = vec.begin(); it != vec.end(); it++)     cout<<*it<<" "; 

} 

錯誤是:

[Error] no matching function for call to 'find(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, const char [6])' 
+2

你錯過了一個'#include '。另外,[擺脫'使用命名空間標準;'](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)。 –

+0

@ SamVarshavchik是對的。請停止使用'using namespace std;' – amanuel2

+1

您需要包含''這是說它無法找到該功能;不是它找不到字符串。你很可能從間接得到std :: string。 –

回答

4

你忘了包括<algorithm>頭,其中std::find生活。

您還應該包含<string>以訪問std::string
你很可能包括<string>間接從另一個頭,不應該依賴它。


既然你正在學習,我會進一步建議你的代碼的現代替代方案。

  1. 相反推擠元件回一個時間,

    std::vector<std::string> vec; 
    vec.push_back("First"); 
    vec.push_back("second"); 
    

    你可以使用初始化列表:

    std::vector<std::string> vec {"First", "Second"}; 
    
  2. 使用for循環,而不是重複添加相同元素,

    for(int i = 0; i < 4 ; i++) 
        vec.push_back("RepeatTimes"); 
    

    您可以使用插入方法:

    vec.insert(vec.end(), 4, "RepeatTimes"); 
    
  3. 考慮推斷類型名稱時,他們很繁瑣,並且不添加任何可讀性值的代碼:基於範圍

    auto fp = std::find(vec.begin(), vec.end(), "First"); 
    
  4. 使用for當遍歷容器的整個範圍時循環:

    for (auto it: vec){ 
        std::cout << it << " "; 
    } 
    
+0

4.替代方法是使用std :: for_each和lamda函數:) –