[英]C++ Find Function Compile Error With std::string
I've been reading Stroustrup's "The C++ Programming Language" to learn how to program in C++, but the following example code from the text book doesn't seem to compile correctly. 我一直在阅读Stroustrup的“ C ++编程语言”以学习如何用C ++进行编程,但是课本中的以下示例代码似乎无法正确编译。
#include <iostream>
#include <iterator>
int main()
{
std::string s = "Hello!";
char c = 'l';
std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
}
int count(const std::string& s, char c)
{
std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);
int n = 0;
while(i != s.end())
{
++n;
i = std::find(i+1, s.end(), c);
}
return n;
}
These are the compile errors: 这些是编译错误:
main.cpp:8:92: error: ‘count’ was not declared in this scope
std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
^
main.cpp: In function ‘int count(const string&, char)’:
main.cpp:13:80: error: no matching function for call to ‘std::basic_string<char>::find(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, char&)’
std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);
What is wrong with my code? 我的代码有什么问题?
The first error tells you that when the compiler reaches main
, it doesn't see any declaration for symbol count
. 第一个错误告诉你,当编译器到达main
,它看不到任何符号count
声明。 This is one of the oddities of C and C++. 这是C和C ++的怪异之一。 To fix it, move the definition of count
up, or merely declare its prototype before main
. 要解决此问题,请向上移动count
的定义,或仅在main
之前声明其原型。
The second error arises because you call the wrong function. 发生第二个错误是因为调用了错误的函数。 From the arguments passed in, I guess you mean std::find
rather than std::string::find
. 从传入的参数来看,我猜你的意思是std::find
而不是std::string::find
。 To get std::find
, you also have to include the header <algorithm>
. 要获取std::find
,还必须包含标题<algorithm>
。
count
method is defined after main
, so it is not visible in main
. count
方法是在main
之后定义的,因此在main
不可见。 Either you have to define it before main
, or you can forward declare count
您必须在main
之前定义它,或者可以转发声明 count
int count(const std::string& s, char c) ;//forward declaration
int main()
{
//code
}
int count(const std::string& s, char c)
{
//code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.