我已经为此工作了近几个小时。我相信我的解决方案在逻辑上是正确的,但是我没有得到想要的输出。例如,假设我想查找字符“h”最后一次出现在这个字符串中的时间:“hlhhhlh”(如果我们从 0 开始,则为 6)。
我的程序可以编译,但它不起作用。此代码仅找出 char 元素中第一次出现“h”的时间。
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int getIndex(vector<char> arr, char t);
int main()
{
vector<char> myArr(0);
myArr.push_back('l');
myArr.push_back('l');
myArr.push_back('l');
myArr.push_back('hlhh');
int i = getIndex(myArr, 'h');
cout << i << endl;
}
int getIndex(vector<char> myArr, char t)
{
int n=0, m=0, count=0;
string y,s;
vector<string> arr(0);
for(int i =0; i < myArr.size(); i++)
{
stringstream st;
st << myArr[i];
st >> y;
arr.push_back(y);
}
stringstream ss;
ss << t;
ss >> s;
for(int i=0; i < arr.size(); i++)
{
if(arr[i] == "h")
{
n++;
}
else if(arr[i] == "l")
{
m++;
}
}
for(int i=0; i< arr.size(); i++)
{
if(arr[i]==s)
{
count++;
if(count == n)
{
return i;
}
else if(count == m)
{
return i;
}
}
}
}