#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <sstream>
using namespace std;
template <int num_rows, int num_cols, int patR, int patC>
int search_for_pattern(int (&grid)[num_rows][num_cols], int indexR, int indexC, int (&pattern)[patR][patC]){
for(int m = 0, i = indexR; m < patR && i < num_rows; m++, i++){
for(int n = 0, j = indexC; n < patC && j < num_cols; n++, j++){
if(grid[i][j] != pattern[m][n]){
return 0;
}
}
}
return 1;
}
int main(){
int T;
cin>>T;
while(T--){
int R, C;
cin>>R>>C;
string* arry = new string[R];
int** int_arry = new int*[R];
for(int i = 0; i < R; ++i)
int_arry[i] = new int[C];
for(int i = 0; i < R; i++){
getline(cin>>ws, arry[i]); //cin >> ws gets rid of leading whitespace
//first so that getline won't think that it's already
//reached the end of the line
//It doesn't seem to take the above input string
}
for(int i = 0; i < R; i++){
for(int j = 0; j < arry[i].length(); j++){
int_arry[i][j] = (int)(arry[i][j] - '0');
//cout<<int_arry[i][j]<<" ";
}
//cout<<endl;
}
//Pattern Array input
int pattern_R, pattern_C;
cin>>pattern_R>>pattern_C;
string* pattern_arry = new string[pattern_R];
int** int_pattern_arry = new int*[pattern_R];
for(int i = 0; i < pattern_R; ++i)
int_pattern_arry[i] = new int[pattern_C];
for(int i = 0; i < pattern_R; i++){
getline(cin>>ws, pattern_arry[i]);
}
for(int i = 0; i < pattern_R; i++){
for(int j = 0; j < pattern_arry[i].length(); j++){
int_pattern_arry[i][j] = (int)(pattern_arry[i][j] - '0');
// cout<<int_pattern_arry[i][j]<<" ";
}
//cout<<endl;
}
int flag = 0, patternTrue = 0;
for(int i = 0; i <= R - pattern_R; i++){
for(int j = 0; j <= C - pattern_C; j++){
if(int_arry[i][j] == int_pattern_arry[i][j]){
flag = 1;
patternTrue = search_for_pattern(int_arry, i, j, int_pattern_arry);
if(patternTrue){
cout<<"YES";
break;
}
}
}
if(patternTrue) break;
cout<<endl;
}
if(flag == 0){
cout<<"NO";
}
//Delete Grid
for(int i = 0; i < R; ++i) {
delete [] int_arry[i];
}
delete [] int_arry;
delete [] arry;
//Delete Pattern
for(int i = 0; i < pattern_R; ++i) {
delete [] int_pattern_arry[i];
}
delete [] int_pattern_arry;
delete [] pattern_arry;
cout<<endl;
}
return 0;
}
在尝试用 C++ 编译上述程序时,我在传递二维数组 int_pattern_arry 和 pattern_arry 时遇到了问题。我正在尝试将二维数组作为引用传递,但我似乎无法继续进行下去。如何将这 2 个数组传递给函数 search_for_pattern?
最佳答案
问题是您正在尝试使用编译时未知的非常量值来初始化您的模板函数。
模板总是在编译时创建,所有必需的数据都必须在那时可用。
以这种方式调整您的搜索功能:
int search_for_pattern(int** grid, int grid_rows, int grid_cols, int** pattern, int pat_rows, int pat_cols, int indexR, int indexC) {
for (int m = 0, i = indexR; m < pat_rows && i < grid_rows; m++, i++) {
for (int n = 0, j = indexC; n < pat_cols && j < grid_cols; n++, j++) {
if (grid[i][j] != pattern[m][n]) {
return 0;
}
}
}
return 1;
}
这样调用:
patternTrue = search_for_pattern(int_arry, R, C, int_pattern_arry, pattern_R, pattern_C, i, j);
关于c++ - 在函数搜索模式中引用二维数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145548/