我正在尝试迭代字符串向量以及字符串的每个字符:
但是我得到一个错误:C++禁止指针和整数之间的比较。
In member function ‘int LetterStrings::sum(std::vector<std::basic_string<char> >)’:
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
以下是我的代码:
#include<iostream>
#include<vector>
#include<typeinfo>
#include<string>
using namespace std;
class LetterStrings {
public:
int sum(vector <string> s) {
int i, j = 0;
int count = 0;
for(i=0;i<s.size();i++) {
for(j=0;j<s[i].length();j++) {
if(s[i][j] != "-") {
count ++;
}
}
}
return count;
}
};
有人可以告诉我,我的代码有什么问题。
** 我对C++真的很陌生。
你的问题在这里:
if(s[i][j] != "-")
它应该是:
if(s[i][j] != '-') // note the single quotes - double quotes denote a character string
既然另一个答案已经确定了您的陈述中的问题,那么这里有一种在一行中实现相同结果的现代化方法:
int count = accumulate(v.begin(), v.end(), 0, [](int p, string s) {
return p + count_if(s.begin(), s.end(), [](char c) {return c != '-';});
});
这个想法是使用 C++11 的 lambda 在二维上执行计数:
-
accumulate
一次遍历一个字符串的向量,并调用顶级 lambda -
count_if
逐个字符遍历字符串,计算非短划线字符的数量。
这是关于 ideone 的演示。