std :: count返回一个值,在执行内部for循环后,对于变量'counter'中的所有字符,我需要将此值重置为0。目的是计算一个字符出现的次数。如果此字符在字符串中出现两次,则将其添加到变量d中。如果出现3次,则将其添加到变量“ e”。
不知道还有什么尝试,或者不确定是否有更好的功能可以达到我的目的。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
int main() {
std::string data;
std::vector<std::string> myString;
std::vector<char> myChar;
int d = 0, e = 0;
std::ifstream inFile;
inFile.open("C:\\Users\\Administrator\\Desktop\\c++ files\\input2.txt");
if (!inFile) {
std::cout << "oops";
}
for (int i = 0; i < 1; i++) {
inFile >> data;
std::copy(data.begin(), data.end(), std::back_inserter(myChar)); //copy from string data to vector myChar via back inserter.
char counter = 'a';
for (int i = 0; i < 26; i++) {
int myCount = std::count(myChar.begin(), myChar.end(), counter);
if (myCount == 2) {
d++;
}
else if (myCount == 3) {
e++;
}
std::cout << "Counter : " << counter << " myCount : " << myCount << "\n";
counter++;
}
}
std::cout << "d is: " << d << "\n";
std::cout << "e is: " << e << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入文件-https://adventofcode.com/2018/day/2
该程序在第一个内部for循环上正确运行,但在第二个以及之后的返回值对于'myCount'变量来说过高(尽管正确)。
std::count不仅会给您一个随机值,还会根据您提供的范围的内容为您提供一个特定的值。您无法更改该行为,而不应该更改。
相反,请查看该范围。为什么不std::count给值,你不要指望?它们要么“太高”,要么是“正确”,不能两者都存在。幸运的是他们是后者。
这是因为您反复std::back_insert访问循环内的向量。随着循环的进行,您将继续计算上次的旧字符!
如果您首先清除myChar,则不会有问题。或者,理想情况下,将myChar循环内部的声明带入。
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |