string::size_type find_char(const string &s, const char c, string::size_type &occurs) { occurs = 0; auto ret = s.size(); for (decltype(s.size()) i = 0; i != s.size(); ++i) { if (s[i] == c) { if (ret == s.size()) { ret = i; } ++occurs; cout << "occurs=" << occurs << endl; } } return ret; } int main() { string s = "jixiansheng"; string::size_type occ = 0; cout << "first: " << find_char(s, 'i', occ) + 1 << "\noccurs: " << occ << endl; cout << "occ=" << occ << endl; getchar(); return 0; }
这是一个用来查找指定字符和记录第一次出现位置的函数。
主函数中引用了occ,但是如上两种输出结果竟然不一样??