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

时间:2017-09-15 14:55:52

标签: c++ distance

我编写了以下程序来打印出以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

3 个答案:

答案 0 :(得分:4)

因为这两个迭代器之间的距离是负的;你有错误的顺序。 &#34;较小的&#34;迭代器应该在左边,而不是右边。

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

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

答案 1 :(得分:3)

  

为什么使用std :: distance会打印出空白-

-字符是减号。它用于表示负数。因此,打印-是因为您打印了负数。距离是负的,因为第一个参数晚于第二个参数。

  

我怎么能摆脱它?

如果计算从早期位置到后者的距离,距离将为正:

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

在这种情况下,你知道,但是如果你不知道或不关心订单而只想要绝对距离,你可以使用std::abs函数来获取它:

std::abs(std::distance(it1, it2));

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

答案 2 :(得分:0)

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

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

或者不使用函数std::distance,您只需编写

即可
auto dist = search - table.begin();

因为类模板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来电,前提是您要包含标题<iterator>

std::cout << std::distance( table, p ) << ' ';
相关问题