无法在Ubuntu上编译c ++程序

时间:2018-01-03 07:41:02

标签: c++ c++11

我无法编译以下程序。我在ubuntu上使用g ++版本5。

#include<iostream>
#include<iterator>
int main()
{
    iterator it;
    return 0;
}

它给了我以下错误,

a.cc: In function ‘int main()’:
a.cc:5:5: error: ‘iterator’ was not declared in this scope
     iterator it;
     ^
a.cc:5:5: note: suggested alternatives:
In file included from /usr/include/c++/5/bits/stl_algobase.h:65:0,
                 from /usr/include/c++/5/bits/char_traits.h:39,
                 from /usr/include/c++/5/ios:40,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from a.cc:1:
/usr/include/c++/5/bits/stl_iterator_base_types.h:118:12: note:   ‘std::iterator’
     struct iterator
            ^
/usr/include/c++/5/bits/stl_iterator_base_types.h:118:12: note:   ‘std::iterator’

1 个答案:

答案 0 :(得分:-2)

迭代器是指向特定容器内的元素的对象。没有全局迭代器类型(这就是编译器出错的原因)。而是标准容器,例如在我下面的示例中,vector<int>定义每个自己的迭代器类型。迭代器通常通过调用容器实例的成员函数来初始化,该函数的元素要迭代。您可以将迭代器视为复杂的指针。

您可以使用向量的内置函数来获取迭代器的特殊值,例如begin()end(),它们允许您遍历它所拥有的所有元素。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    // Declaring a vector
    vector<int> v = { 1, 2, 3 };

    // Declaring an iterator
    vector<int>::iterator i;

    // Accessing the elements through iterators
    // using functions from vector<int>
    for (i = v.begin(); i != v.end(); ++i)
    {
        cout << *i << " ";
    }
}