【问题标题】:Does using the iterator member function "empty()" only work on certain vector types?使用迭代器成员函数“empty()”是否仅适用于某些向量类型?
【发布时间】:2017-07-23 08:09:01
【问题描述】:

当我在 int 类型的向量上使用迭代器成员函数“empty()”时出现错误,而不是在 string 类型的向量上(根据我的理解使用正确的术语)。

int 类型的向量:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    vector<int> ivec = {0,1,2};
    auto iter = ivec.begin();
    if(!iter->empty())
        cout << "not empty" << endl;

    return 0;
}

输出:

error C2839: invalid return type 'int *' for overload 'operator ->'
error C2039: 'empty': is not a member of 'std::Vector_iterator....'

字符串类型的向量:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    vector<string> svec = {"text"};
    auto iter = svec.begin();
    if(!iter->empty())
        cout << "not empty" << endl;

    return 0;
}

输出:

not empty

更新

  • 我现在了解到,根据向量中的类型,您只能执行某些操作。
  • 您不是对迭代器本身执行操作(因为它是指向容器中元素的指针),而是对迭代器指向的对象执行操作。

【问题讨论】:

  • 您在问int 是否与string 不同。是的。
  • 表 3.6。 C++ Primer,Stanley B. Lippman、Josée LaJoie、Barbara E. Moo:标准容器迭代器操作:*iter、iter-> 等。这里发生了什么?请解释一下?
  • 我们没有你的书。更新此问题或发布另一个具有足够上下文的完整问题。见minimal reproducible example
  • @John 该表是否将empty() 列为标准容器迭代器操作?
  • @juanchopanza 它没有。但我认为它暗示了这一点。我明白现在发生了什么。

标签: c++ c++11 visual-c++


【解决方案1】:

empty() 不是“迭代器成员函数”。您没有在迭代器上调用 empty() - 您正在取消引用迭代器,并在迭代器引用的向量元素上调用 empty()。如果将iter-&gt;empty() 替换为等效形式(*iter).empty() 可能会更清楚

换句话说,

auto iter = vec.begin();
iter->empty();

等价于

vec[0].empty();

这里根本不涉及迭代器;希望这会让这一点更加清楚。

现在,碰巧std::string 确实有一个成员函数empty(),而int 当然没有(因为它不是类类型,所以不能有任何成员函数)。这就是为什么您的代码使用 vector&lt;string&gt; 而不是 vector&lt;int&gt; 编译的原因。

【讨论】:

    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    相关资源
    最近更新 更多