C++ 中的无限 for
Infinite for in C++
我想一遍又一遍地循环 std::vector
直到我从循环中跳出。这是最好的方法吗?
int main() {
std::string str;
std::ifstream infile;
std::vector<int> vec;
std::set<int> sums;
int sum = 0;
sums.insert(sum);
infile.open("Text.txt");
while (!infile.eof()) {
getline(infile, str);
vec.push_back(std::stoi(str));
}
infile.close();
while (true) {
for (int i : vec) {
sum += i;
if (sums.count(sum)) {
std::cout << sum;
return 0;
}
sums.insert(sum);
}
}
}
您可以使用算法库并执行以下操作:
std::vector<int> vec;
// initialize vec here
while (std::none_of(vec.begin(), vec.end(), [](int i) {
// return true here to break
return false;
}));
我想一遍又一遍地循环 std::vector
直到我从循环中跳出。这是最好的方法吗?
int main() {
std::string str;
std::ifstream infile;
std::vector<int> vec;
std::set<int> sums;
int sum = 0;
sums.insert(sum);
infile.open("Text.txt");
while (!infile.eof()) {
getline(infile, str);
vec.push_back(std::stoi(str));
}
infile.close();
while (true) {
for (int i : vec) {
sum += i;
if (sums.count(sum)) {
std::cout << sum;
return 0;
}
sums.insert(sum);
}
}
}
您可以使用算法库并执行以下操作:
std::vector<int> vec;
// initialize vec here
while (std::none_of(vec.begin(), vec.end(), [](int i) {
// return true here to break
return false;
}));