0

我有一个字符串的三维数组,我想创建一个函数来计算矩阵中有多少字符串在位置 k 中有字符 c。我做了这个功能:

#include <vector>
#include <string>
using namespace std;

typedef vector <string> Row;
typedef vector <Row> Matrix;

int numer_of_words (const Matrix& m, char c, int k) {
    int sum = 0;
    int rows = m.size();
    for (int i=0; i < rows; ++i) {
        int words = m[i].size();
        for (int j=0; j < words; ++j) {
            string s = m[i][j];
            if (s.length() <= k) {
                if (s[k] == c) ++sum;
            }
        }

    }
    return sum;
}

换句话说,当 s[k] = c (如果 s[k] 存在)时 sum 应该增加。我没有收到编译错误,但代码不起作用。

4

1 回答 1

0
if (s.length() <= k) {
    if (s[k] == c) ++sum;
}

Here you access s[k] only if s's length is less than or equal to k, which is the opposite of what you want. The condition should be s.length() > k.

于 2013-04-26T16:06:30.137 回答