为什么 std::distance 打印出一个 `-`?

Why does std::distance print out a `-`?

我编写了以下程序来打印以 a=0b=1 等开头的字母表的出现。有人可以指出为什么使用 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

因为这两个迭代器之间的距离是负数;你把它们放在错误的顺序。 "lesser" 迭代器应该在左边,而不是右边。

您有:std::distance(search, table.begin())

你应该有:std::distance(table.begin(), search)

why using std::distance is printing out a blank -

-字符是减号。它用于表示负数。所以, - 被打印出来是因为你打印了负数。距离为负,因为第一个参数比第二个参数晚。

how I could get rid of it?

如果计算前面位置到后面位置的距离,则距离为正:

std::distance(table.begin(), search);

在这种情况下你确实知道,但如果你不知道或不关心顺序并且只想要绝对距离,你可以使用函数 std::abs:

来获取它
std::abs(std::distance(it1, it2));

PS。仅当迭代器是随机访问时才允许先传递后一个迭代器。

标准函数 std::distance 接受类型 [start, target] 的范围。所以你需要写

auto dist = std::distance( table.begin(), search );

或者不使用函数 std::distance 你可以只写

auto dist = search - table.begin();

因为 class 模板 std::vector 具有随机访问迭代器。

关于程序的几句话。

在这种情况下,最好使用 C 字符串而不是像 std::vector 这样的标准容器,并且相应地使用标准 C 函数而不是 C++ 算法。

程序可以如下所示

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

int main() 
{
    const char *table = "abcdefghijklmnopqrstuvwxyz";
    std::string s;

    std::getline( std::cin, s );

    for ( char c : s )
    {
        c = std::tolower( ( unsigned char )c );

        if ( const char *p = std::strchr( table, c ) )
        {
            std::cout << p - table << ' ';
        }
    }

    std::cout << std::endl;

    return 0;
}

如果输入

Umedh Singh Bundela 

那么输出看起来像

20 12 4 3 7 18 8 13 6 7 1 20 13 3 4 11 0

而不是语句中的表达式

std::cout << p - table << ' ';

如果你愿意,你可以使用 std::distance 的调用,前提是你要包含 header <iterator>

std::cout << std::distance( table, p ) << ' ';