我写了下面的程序打印出一个以a=0
,b=1
等开头的字母。有人可能请指出为什么使用std :: distance打印出一个空白的-
以及我如何摆脱它?为什么std :: distance会打印一个`-`?
// Example program
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
string str;
cin>>str;
int n=str.size();
std::vector<char> table(26);
table = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
int i=0;
while(i<n) {
char c=str[i];
auto search = std::find(table.begin(), table.end(), c);
if(search!=table.end()) {
int dist = std::distance(search, table.begin());
cout<<dist; //prints out -0-1-2-3 instead of 0123, why?
}
i++;
}
return 0;
}
工作程序是here
你确定它打印'-'零之前?当我尝试它时,它不会。 –
在你链接你确实有正确的方式dist dist dist = std :: distance(table.begin(),search);但你的代码是不同的 –
@HariomSingh,那是因为我稍后改变了它。 –