C++ 如何查找数组中值的倒数第二次出现的索引?
例如,如果我有一个类似于C++ 如何查找数组中值的倒数第二次出现的索引?,c++,C++,例如,如果我有一个类似于[1,1,3,5,2,0,0,5,7]的数组,元素5最近出现的位置将在第4个索引处(考虑到数组是从1开始索引的)。简单方法: 有两个变量,matchingIndex和lastMatchingIndex(将它们初始化为-1或明显的值) 在数组中循环 遇到匹配时,将matchingIndex移动到lastmachingindex,然后将当前索引放入matchingIndex 到达末尾后,lastmachingindex包含所需的索引(基于0!),除非它是-1,这意味着没有两个
[1,1,3,5,2,0,0,5,7]
的数组,元素5最近出现的位置将在第4个索引处(考虑到数组是从1开始索引的)。简单方法:
matchingIndex
和lastMatchingIndex
(将它们初始化为-1或明显的值)matchingIndex
移动到lastmachingindex
,然后将当前索引放入matchingIndex
lastmachingindex
包含所需的索引(基于0!),除非它是-1,这意味着没有两个匹配项matchingIndex
和numMatches
(将后者初始化为0)matchingIndex
并递增numMatches
numMatches
为2,则停止numMatches
不是2,则没有两个匹配项,因此没有结果#include <vector>
#include <iostream>
int main()
{
const std::vector<int> v{1, 1, 3, 5, 2, 0, 0, 5, 7};
const int searchFor = 5;
int matchingIndex = -1;
int numMatches = 0;
for (int i = v.size()-1; i >= 0; --i)
{
if (v[i] == searchFor)
{
numMatches++;
matchingIndex = i;
if (numMatches == 2)
break; // no point continuing!
}
}
if (numMatches == 2)
std::cout << "Found second-to-last instance of '" << searchFor << "' at index " << matchingIndex << '\n';
else
std::cout << "No matches, or only one match\n";
}
#包括
#包括
int main()
{
常数std::向量v{1,1,3,5,2,0,0,5,7};
const int searchFor=5;
int matchingIndex=-1;
整数匹配=0;
对于(int i=v.size()-1;i>=0;--i)
{
如果(v[i]==搜索)
{
numMatches++;
匹配指数=i;
if(numMatches==2)
break;//继续下去没有意义!
}
}
if(numMatches==2)
std::cout你将如何手工操作?一旦你做到了,就把这个过程转化为代码。从集合的后面循环并获取第二个匹配项怎么样?@Jayden Nightshade你是在试图找到第二个匹配项5的位置吗?
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
const std::vector<int> v{1, 1, 3, 5, 2, 0, 0, 5, 7};
const int searchFor = 5;
// First match from end
auto it = std::find(std::rbegin(v), std::rend(v), searchFor);
// Second match from end
if (it != std::rend(v))
it = std::find(it+1, std::rend(v), searchFor);
if (it != std::rend(v))
std::cout << "Found second-to-last instance of '" << searchFor << "' at index " << std::distance(std::begin(v), it.base()) << '\n';
else
std::cout << "No matches, or only one match\n";
}