📜  C / C++中的迭代器和指针之间的区别以及示例

📅  最后修改于: 2021-05-30 08:01:49             🧑  作者: Mango

指针:指针是一个变量,其中包含另一个变量的地址,即该变量的存储位置的地址。像任何变量或常量一样,我们必须在使用指针存储任何变量地址之前声明一个指针。

句法:

type* var_name;

例子:

// The output of this program can be different
// in different runs. Note that the program
// prints address of a variable and a variable
// can be assigned different address in different
// runs.
#include 
  
int main()
{
    int x;
  
    // Prints address of x
    printf("%p", &x);
  
    return 0;
}
输出:
0x7ffcac5ae824

迭代器:迭代器是任何对象,它指向一系列元素(例如数组或容器)中的某个元素,并具有遍历该范围元素的能力。

句法:

type_container :: iterator var_name;

例子:

// C++ program to demonstrate iterators
  
#include 
#include 
using namespace std;
int main()
{
    // Declaring a vector
    vector v = { 1, 2, 3 };
  
    // Declaring an iterator
    vector::iterator i;
  
    int j;
  
    cout << "Without iterators = ";
  
    // Accessing the elements without using iterators
    for (j = 0; j < 3; ++j) {
        cout << v[j] << " ";
    }
  
    cout << "\nWith iterators = ";
  
    // Accessing the elements using iterators
    for (i = v.begin(); i != v.end(); ++i) {
        cout << *i << " ";
    }
  
    // Adding one more element to vector
    v.push_back(4);
  
    cout << "\nWithout iterators = ";
  
    // Accessing the elements without using iterators
    for (j = 0; j < 4; ++j) {
        cout << v[j] << " ";
    }
  
    cout << "\nWith iterators = ";
  
    // Accessing the elements using iterators
    for (i = v.begin(); i != v.end(); ++i) {
        cout << *i << " ";
    }
  
    return 0;
}
输出:
Without iterators = 1 2 3 
With iterators = 1 2 3 
Without iterators = 1 2 3 4 
With iterators = 1 2 3 4

迭代器和指针之间的区别:
迭代器和指针的相似之处在于我们可以取消引用它们以获得值。但是,主要区别如下:

Pointers Iterators
A pointer hold an address in memory. An iterator may hold a pointer, but it may be something much more complex. For example, an iterator can iterate over data that’s on file system, spread across many machines, or generated locally in a programmatic fashion.
A good example is an iterator over linked list, the iterator will move through elements that are at nodes in the list whose addresses in RAM may be scattered.
We can perform simple arithmetic on pointers like increment, decrement, add an integer etc. Not all iterators allow these operations, e.g., we cannot decrement a forward-iterator, or add an integer to a nonrandom-access iterator.
A pointer of type T* can point to any type T object. An iterator is more restricted, e.g., a vector::iterator can only refer to doubles that are inside a vector container.
We can delete a pointer using delete Since an iterator refers to objects in a container, unlike pointers, there’s no concept of delete for an iterator. (The container is responsible for memory management.)
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”