【问题标题】:Convert iterator to int将迭代器转换为 int
【发布时间】:2011-09-02 10:37:34
【问题描述】:
int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;

我正在尝试查找向量中元素的索引。 iterators 没问题,但我希望它为 int。我该怎么做?

【问题讨论】:

    标签: c++ vector iterator


    【解决方案1】:

    您可以为此使用std::distance

    i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );
    

    不过,您可能需要检查您的索引是否超出范围。

    if( i == names.size() )
        // index out of bounds!
    

    不过,在使用 std::distance 之前使用迭代器执行此操作可能更清楚。

    std::vector<std::string>::iterator it = std::find( names.begin(), names.end(), s );
    
    if( it == names.end() )
         // not found - abort!
    
    // otherwise...
    i = std::distance( names.begin(), it );
    

    【讨论】:

      【解决方案2】:
      std::vector<string>::iterator it = std::find(names.begin(), names.end(), s);
      if (it != names.end()) {
          std::cout << std::distance(names.begin(), it);
      } else {
          // ... not found
      }
      

      【讨论】:

        【解决方案3】:

        试试

        i = (find( names.begin(), names.end(), s ) - names.begin());  
        

        编辑: 虽然您应该考虑使用 vector::size_type 而不是 int。

        【讨论】:

        • @thetux4:不应该。当你减去两个迭代器时,你应该得到一个差异类型,std::vector&lt;std::string&gt;::iterator 是一个整数类型。
        • 是的,我知道 ;) 这就是为什么你应该使用我的线路而不是你的线路。 find() 返回一个迭代器并从该迭代器中减去 names.begin() 得到一个 vector::size_type。 (无符号整数类型 - 可能类似于 unsinged long)
        • 嘿!如果您将“i = ...”行替换为我的行,则效果很好。
        • 迭代器减法的结果不是size_type,它是difference_type,默认ptrdiff_t,并且始终是有符号类型。
        【解决方案4】:

        我对您的代码所做的假设:

        using std::vector;
        using std::cout;
        using std::string;
        

        如果我的假设是正确的,那么您可以在vector 的开头和iterator 之间的finddistance(基本上是vector 的索引,您可以在其中找到这样的元素):

        using std::distance;
        

        就这样……

        vector<string>::iterator i = find(names.begin(), names.end(), s);
        if (i != names.end())
        {
            cout << "Index " << std::distance(names.begin(), i);
        }
        else
        {
            cout << s << "not found";
        }
        

        【讨论】:

          【解决方案5】:

          你可以取消引用你的迭代器

          int i = *name;
          

          【讨论】:

            猜你喜欢
            • 2015-01-15
            • 2020-05-18
            • 1970-01-01
            • 1970-01-01
            • 2016-12-14
            • 2021-08-26
            • 2010-10-19
            • 2012-04-24
            • 2021-12-15
            相关资源
            最近更新 更多