【发布时间】:2020-06-23 19:44:03
【问题描述】:
这是我的txt 文件,其中第一行是dataSets 的编号。第 2 行(size1 变量)等于第 3 行(A1 数组)中的元素数,第 4 行(size2 变量)等于第 5 行(A2 数组)中的元素数。我的 readFile 函数必须覆盖上面列出的变量和数组,而不覆盖 dataSets 变量。
我的countElementsInArray 函数是计算数组A2 中数组A1 中数字的出现次数。在显示名为计数的向量时遇到问题。我可以在调试器中看到从 fcount 函数返回的元素正在传递给向量计数,但无法输出该向量(程序停在那里)。
该程序的想法是使向量数组命名为counts,其中数组A2中的数字出现次数在数组A1中。
txt:
3
4
-5 -1 0 8
7
7 9 2 0 -7 2 -5
4
1 2 3 4
2
1 1
5
0 0 0 0 0
1
3
Result for above input should be:
Dataset1:
0 0 0 1 0 0 1
Dataset2:
1 1
Dataset3:
0
int main() {
std::fstream file;
openFile(file);
std::vector<int> v1,v2;
fread(file, v1, v2);
file.close();
return 0;
}
void fread(std::fstream &file, std::vector<int> &A1, std::vector<int> &A2) {
std::vector<int> counts;
int dataSets, size1, size2, x, y;
file >> dataSets;
for (size_t i = 0; i < dataSets; i++) {
file >> size1;
for (size_t j = 0; j < size1; j++) {
file >> x;
A1.push_back(x);
}
file >> size2;
for (size_t j = 0; j < size2; j++) {
file >> y;
A2.push_back(y);
}
for (size_t j = 0; j < size2; j++) {
int searchValue = A2[j];
counts.push_back(fcount(A1, size1, searchValue));
}
int numberOfDataSet = i + 1;
std::cout << "Dataset" << numberOfDataSet << ":" << std::endl;
for(auto& k : counts)
std::cout << k;
std::cout << std::endl;
}
}
int fcount(std::vector<int> &A, int size, int searchValue) {
int count = 0, first = 0, last = size;
int i = 1;
int j = 1;
while (first <= last) {
int mid = first + (last - 1) / 2;
if (A[mid] == searchValue) {
count++;
do {
if (A[mid + i] == searchValue && A[mid - j] == searchValue) {
count += 2;
i++;
j++;
} else if (A[mid + i] == searchValue) {
count++;
i++;
} else if (A[mid - j] == searchValue) {
count++;
j++;
}
return count;
} while (A[mid + i] == searchValue || A[mid - j] == searchValue);
} else if (searchValue < A[mid])
last = mid - 1;
else if (searchValue > A[mid])
first = mid + 1;
}
return count;
}
【问题讨论】:
-
仅供参考,
std::set<int>代替std::vector<int>和std::set_intersection而不是您现在拥有的所有代码,使这个程序变得微不足道。 -
@John “我在显示向量命名计数时遇到问题。我可以在调试器中看到从 fcount 函数返回的元素正在传递给向量计数,但无法输出此向量(程序停在那里)。”正如我所说,计数向量有一个很好的值!我遇到的问题与从向量中输出值有关。
-
评论部分的原因是针对 cmets,而不是答案。我评论说代码可以更简单。
-
你的向量
counts也应该在 for 循环中声明。