簡體   English   中英

在向量上使用迭代器時,“ std :: bad_alloc”甚至錯誤的向量大小

[英]'std::bad_alloc' or even wrong vector size when using iterator on vector

嘗試將其他字符串推到向量的中間時terminate called after throwing an instance of 'std::bad_alloc'我被terminate called after throwing an instance of 'std::bad_alloc' 我使用g ++ 4.8.2。

當在coliru上使用g ++ 5.2時size of str_vector 0: 1, size of str_vector 1: 1我什至輸出了錯誤的向量大小, size of str_vector 0: 1, size of str_vector 1: 1

當我使用索引(例如str_vector[0] )訪問向量或使用std::list時,程序可以正常工作。

這是否意味着對iterator的使用有一些限制? 我假設使用索引或迭代器訪問向量時應該沒有任何區別。

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

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

int main() {
        vector<vector<string>> str_vector;

        str_vector.emplace_back();
        vector<vector<string>>::iterator it0 = std::prev(str_vector.end());
        it0->push_back("a");

        str_vector.emplace_back();
        vector<vector<string>>::iterator it1 = std::prev(str_vector.end());
        it1->push_back("a");

        it0->push_back("a"); // bad alloc here

        std::cerr << "size of str_vector 0: " << it0->size() << std::endl;
        std::cerr << "size of str_vector 1: " << it1->size() << std::endl;

        return 0;
}

將元素添加到向量時,可能需要重新分配其內部存儲器,這將導致所有迭代器變為無效。 因此,在執行第二個emplace_back ,第一個迭代器it0無效。

迭代器不過是面向對象的指針。 迭代器無效與指針無效非常相似。

C ++規范:

向量:插入點之前的所有迭代器和引用均不受影響,除非新的容器大小大於先前的容量(在這種情況下,所有迭代器和引用均無效)[23.2.4.3/1]

第一次執行下面的代碼行是有效的,第二次使用相同的迭代器執行此迭代器,則該迭代器已失效:

    it0->push_back("a"); // bad alloc here

為了知道什么是迭代器無效以及如何處理,這里有一篇關於迭代器無效的精彩文章:

[ 迭代器失效規則

暫無
暫無

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

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