#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int s;
std::cin >> s;
std::vector<int> numbers;
for(int i{1}; i <= s; i++) {
int num_input;
std::cin >> num_input;
numbers.push_back(num_input);
}
int c_s;
std::cin >> c_s;
while(c_s--) {
int n;
std::cin >> n;
if(std::find(numbers.begin(),numbers.end(), n) != numbers.end()) {
std::cout << "Yes" << std::endl;
} else {
std::cout << "No" << std::endl;
}
}
}
黑客排名上有一个编码问题,要我在找到它时显示int的索引,但我想不出任何办法。有更简单的方法吗?
您可以std::distance
在返回的迭代器上使用索引std::find
。您可以按以下方式更改代码
std::vector<int>::iterator it = std::find(numbers.begin(),numbers.end(),n);
if(it != numbers.end()) {
std::cout << "Yes, found at" << std::distance(numbers.begin(),it) << std::endl;
} else {
std::cout << "No" << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句