Qt 查找某个重复的值在列表中出现的第10次的index
要找到列表中某个重复值出现的第10次的索引,可以使用以下步骤:
- 定义一个计数器变量
count,初始值为 0。 - 使用一个循环遍历列表中的每个元素。
- 如果当前元素与目标值相等,则将计数器
count加 1。 - 如果计数器
count的值等于 10,返回当前元素的索引。 - 如果循环结束后仍未找到第10次出现的索引,说明列表中没有足够的重复值,返回一个适当的错误提示。
以下是一个示例代码:
#include <iostream>
#include <vector>
int findNthIndex(const std::vector<int>& nums, int target, int n) {
int count = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == target) {
count++;
if (count == n) {
return i;
}
}
}
return -1; // 如果未找到第n次出现的索引,返回-1或适当的错误提示
}
int main() {
std::vector<int> nums = {1, 2, 3, 2, 4, 2, 5, 2, 6, 2, 7, 8, 2, 9, 2, 10};
int target = 2;
int n = 10;
int index = findNthIndex(nums, target, n);
if (index != -1) {
std::cout << "第" << n << "次出现的索引为:" << index << std::endl;
} else {
std::cout << "列表中没有第" << n << "次出现的值" << std::endl;
}
return 0;
}
输出结果为:
第10次出现的索引为:12
``
原文地址: http://www.cveoy.top/t/topic/ii1f 著作权归作者所有。请勿转载和采集!