簡體   English   中英

使用const_iterator時為什么可以在向量中插入元素

[英]Why elements can be inserted in a vector when using const_iterators

考慮下面的代碼,

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(){
    vector<int> value{22, 23, 25, 34, 99};
    auto it = find(value.cbegin(), value.cend(), 25);
    value.insert(it, 77);
    return 0;
}

在這里it是一個const_iterator 在插入之前,它指向25 插入后,它指向77 這不會被視為修改嗎?

const_iterator阻止您修改迭代器指向的元素,它不會阻止您修改容器本身。

在您的示例中,您將找到元素25的迭代器,並在25之前插入77 你沒有修改值25

在插入之前, it指向25 插入后,它指向77

vector::insert總是使插入點處和之后的迭代器無效。 因此,如果在insert后在示例中取消引用it ,則它是未定義的行為。 相反,你可以做到

it = value.insert(it, 77);
// it points to 77, the newly inserted element
// (it + 1) points to 25

cosnt_iterator指向const值。 這意味着當你取消引用它然后它將返回const對象。 可以修改迭代器,但不能修改迭代器指向的對象。

vector<int> value{22, 23, 25, 34, 99};
std::vector<int>::const_iterator it = find(value.cbegin(), value.cend(), 25);
it = value.insert(it, 77); // valid 
*it = 77;                  // Error

Think就像指向const對象的指針。 當你申報時

int const a = 10;
int const *ptr = &a;

然后可以修改ptr但對象ptr指向不應該。

*ptr = 5         // Error
int const b = 0;
ptr = &b;        // Valid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM