我在C++11中有这个函数:
bool ccc(const string cc) {
vector<string> digits;
int aux;
for(int n = 0; n < cc.length(); ++n) {
digits.push_back(to_string(cc[n])); }
for(int s = 1; s < digits.size(); s += 2) {
aux = stoi(digits[s]);
aux *= 2;
digits[s] = to_string(aux);
aux = 0;
for(int f = 0; f < digits[s].length(); ++f) {
aux += stoi(digits[s][f]); }
digits[s] = to_string(aux);
aux = 0; }
for(int b = 0; b < digits.size(); ++b) {
aux += stoi(digits[b]); }
aux *= 9;
aux %= 10;
return (aux == 0); }
当使用带有
-std=c++11
标志的 g++ 进行编译时,我收到此错误:
crecarche.cpp: In function ‘bool ccc(std::string)’:
crecarche.cpp:18:12: error: no matching function for call to ‘stoi(__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&)’
18 | aux += stoi(digits[s][f]); }
| ~~~~^~~~~~~~~~~~~~
但是我之后使用了
stoi
函数,并且该行没有出现任何错误。
为什么编译器会向我抛出此错误以及如何修复它?
错误消息告诉您传递给
stoi
的参数属于以下类型
__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&
这是
char&
的一种奇特说法。发生这种情况是因为 digits[s]
已经是 string&
类型,进一步订阅它会给你一个 char&
。
我不清楚你想要实现什么目标。也许您需要删除多余的下标,或者使用
digits[s][f] - '0'
来计算数字值。 C++ 要求十进制数字由后续代码点表示,因此即使在不基于 Unicode 的 ISO 646 子集的理论实现中,这也适用。