C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] - نسخه متنی

Herb Sutter, Andrei Alexandrescu

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


Discussion


You can insert elements into sequences at different points using

insert , and you can append elements to sequences in various ways including:

vector<int> vec;

// vec is empty
vec.resize(vec.size() + 1, 1);

// vec contains { 1 }
vec.insert(vec.end(), 2);

// vec contains { 1, 2 }
vec.push_back(3);

// vec contains { 1, 2, 3 }

Of all forms,

push_back alone takes

amortized constant time. The other forms' performance can be as bad as quadratic. Needless to say, beyond small data volumes that makes those alternatives potential scalability barriers. (See Item 7)

push_back 's magic is simple: It expands capacity exponentially, not by a fixed increment. Hence the number of reallocations and copies decreases rapidly with size. For a container populated using only

push_back calls, on average each element has been copied only onceregardless of the final size of the container.

Of course,

resize and

insert could employ the same strategy, but that is dependent on the implementation; only

push_back offers the guarantee.

Algorithms can't call

push_back directly because they don't have access to the container. You can ask algorithms to use

push_back anyway by using a

back_inserter .


/ 521