Вопрос

I have a vector in my Header file, and I'm trying to do a bool function that returns the find() function, but it is giving me an error.

vector<string> reservedWord{
....
....
....
};

bool function

bool isReservedWord(string str)
{
   return find(reservedWord.begin(), reservedWord.end(), str) != reservedWord.end();
}

I tried it both without the last != reservedWord.end) and also without.

The errors given are these:

||=== Build: Release in compilers (compiler: GNU GCC Compiler) ===|
E:\University\compilers\reservedWords.h||In function 'bool isReservedWord(std::string)':|
E:\University\compilers\reservedWords.h|40|error: no matching function for call to 'find(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&)'|
E:\University\compilers\reservedWords.h|40|note: candidate is:|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note: template<class _CharT2> typename __gnu_cxx::__enable_if<std::__is_char<_CharT2>::__value, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> > >::__type std::find(std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, const _CharT2&)|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note:   template argument deduction/substitution failed:|
E:\University\compilers\reservedWords.h|40|note:   '__gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >' is not derived from 'std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >'|
E:\University\compilers\reservedWords.h|41|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
Это было полезно?

Решение

Here's a working example. Look at how your code is different. Ask questions as required. :-)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> g_reserved
{
    "the",
    "quick", 
    "brown", 
    "fox", 
    "jumps", 
    "over",
    "the",
    "lazy",
    "dog"
};

bool IsReserved(const std::string &s)
{
    return g_reserved.end() !=
           std::find(g_reserved.cbegin(), g_reserved.cend(), s);
}

int main() 
{
    std::cout << std::boolalpha
              << IsReserved("fox")
              << ' '
              << IsReserved("zebra")
              << std::endl;

    return 0;
}

Другие советы

I got the same compilation error when <string> was included but <algorithm> was not. In that case the compiler only sees the declaration of

std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&)

and quits with this error.

To fix this, add

#include <algorithm>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top