迭代向量字符串的字符(C++禁止指针和整数之间的比较)
我试图迭代字符串向量,以及字符串的每个字符: <>但是我有一个错误:C++禁止指针和整数的比较。迭代向量字符串的字符(C++禁止指针和整数之间的比较),c++,C++,我试图迭代字符串向量,以及字符串的每个字符: 但是我有一个错误:C++禁止指针和整数的比较。 In member function ‘int LetterStrings::sum(std::vector<std::basic_string<char> >)’: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]| 以下是我的代码: #include<iostre
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的lambdas在两个维度上执行计数:
累计每次遍历向量一个字符串,并调用顶级lambda
count_如果逐个字符遍历字符串,则计算非破折号字符的数量。
这是一个。哦!那太容易了。谢谢