簡體   English   中英

編譯器錯誤:沒有匹配的函數可供調用查找

[英]Compiler Error: No matching function for call to find

我剛開始學習時試圖使用向量,但被這個錯誤所困擾。 我試圖查看 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])'

您忘記在std::find所在的位置包含<algorithm>標頭。

您還應該包含<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 << " "; }

添加:

#include <algorithm>

解決了我的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM