std::vector assign() method

  • since C++20
  • since C++11
  • until C++11

Replaces the contents of the container with the contents of another.

(1) Replaces the contents with count copies of value value .

(2) Replaces the contents with copies of those in the range [ first, last ) .

The behavior is undefined

This overload participates in overload resolution only if InputIt satisfies LegacyInputIterator .

This overload has the same effect as overload (1) if InputIt is an integral type.

(3) Replaces the contents with the elements from the initializer list ilist .

All iterators , pointers and references to the elements of the container are invalidated. The past-the-end iterator is also invalidated.

Parameters ​

  • count - the new size of the container
  • value - the value to initialize elements of the container with
  • first , last - the range to copy the elements from
  • ilist - initializer list to copy the values from

Return value ​

Complexity ​.

  • (1) Linear in count - O(count) .
  • (2) Linear in distance between first and last - O(std::distance(firs,t last)) .
  • (3) Linear in ilist.size() - O(ilist.size()) .

Exceptions ​

  • Return value

The C++ Standard Library

  • The C Standard Library
  • The C++ Standard Library
  • C++ Library - Home
  • C++ Library - <fstream>
  • C++ Library - <iomanip>
  • C++ Library - <ios>
  • C++ Library - <iosfwd>
  • C++ Library - <iostream>
  • C++ Library - <istream>
  • C++ Library - <ostream>
  • C++ Library - <sstream>
  • C++ Library - <streambuf>
  • C++ Library - <atomic>
  • C++ Library - <complex>
  • C++ Library - <exception>
  • C++ Library - <functional>
  • C++ Library - <limits>
  • C++ Library - <locale>
  • C++ Library - <memory>
  • C++ Library - <new>
  • C++ Library - <numeric>
  • C++ Library - <regex>
  • C++ Library - <stdexcept>
  • C++ Library - <string>
  • C++ Library - <thread>
  • C++ Library - <tuple>
  • C++ Library - <typeinfo>
  • C++ Library - <utility>
  • C++ Library - <valarray>
  • The C++ STL Library
  • C++ Library - <array>
  • C++ Library - <bitset>
  • C++ Library - <deque>
  • C++ Library - <forward_list>
  • C++ Library - <list>
  • C++ Library - <map>
  • C++ Library - <queue>
  • C++ Library - <set>
  • C++ Library - <stack>
  • C++ Library - <unordered_map>
  • C++ Library - <unordered_set>
  • C++ Library - <vector>
  • C++ Library - <algorithm>
  • C++ Library - <iterator>
  • C++ Programming Resources
  • C++ Programming Tutorial
  • C++ Useful Resources
  • C++ Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C++ Vector Library - assign() Function

Description.

The C++ function std::vector::assign() assign new values to the vector elements by replacing old ones. It modifies size of vector if necessary.

If memory allocation happens allocation is allocated by internal allocator.

New contents are the copies of values passed as initializer list, in the same order.

Declaration

Following is the declaration for std::vector::assign() function form std::vector header.

ilist − Initializer list to assign values to vector.

Return value

This member function never throws exception.

Time complexity

Linear i.e. O(n)

The following example shows the usage of std::vector::assign() function.

Let us compile and run the above program, this will produce the following result −

std::vector:: assign

(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Member functions

(C++11)
assign( size_type count, const T& value ); (1)
< class InputIt >
void assign( InputIt first, InputIt last );
(2)
assign( <T> ilist ); (3)

Replaces the contents of the container.

1) replaces the contents with count copies of value value

2) replaces the contents with copies of those in the range [first, last)

3) replaces the contents with the elements from the initializer list ilist .

Parameters Complexity Example See also

[ edit ] Parameters

count - the new size of the container
value - the value to initialize elements of the container with
first, last - the range to copy the elements from
ilist - initializer list to copy the values from
Type requirements
- must meet the requirements of .

[ edit ] Complexity

1) linear in count

2) linear in distance between first and last

3) linear in ilist. size ( )

[ edit ] Example

The following code uses assign to add several characters to a std:: vector < char > :

[ edit ] See also

constructs the
(public member function)

std::vector<T,Allocator>:: assign

(C++20)
(C++20)
(C++11)
(C++11)
(C++11)
(C++17)
Member functions
Element access
Iterators
vector::cbegin (C++11)
vector::cend (C++11)
vector::crbegin (C++11)
vector::crend (C++11)
Capacity
Modifiers
(C++17)
assign( size_type count, const T& value ); (1)
< class InputIt >
void assign( InputIt first, InputIt last );
(2)
assign( <T> ilist ); (3) (since C++11)

Replaces the contents of the container.

This overload has the same effect as overload (1) if is an integral type. (until C++11)
This overload only participates in overload resolution if satisfies . (since C++11)

All iterators, pointers and references to the elements of the container are invalidated. The past-the-end iterator is also invalidated.

count - the new size of the container
value - the value to initialize elements of the container with
first, last - the range to copy the elements from
ilist - initializer list to copy the values from

The following code uses assign to add several characters to a std:: vector < char > :

constructs the
(public member function)

std::vector<T,Allocator>::assign

(1)
(until C++20)
(since C++20)
(2)
(until C++20)
(since C++20)
(3)
(since C++11)
(until C++20)
(since C++20)

Replaces the contents of the container.

This overload has the same effect as overload (1) if is an integral type.

(until C++11)

This overload participates in overload resolution only if satisfies .

(since C++11)

All iterators, pointers and references to the elements of the container are invalidated. The past-the-end iterator is also invalidated.

count - the new size of the container
value - the value to initialize elements of the container with
first, last - the range to copy the elements from
ilist - initializer list to copy the values from

The following code uses assign to add several characters to a std:: vector < char > :

constructs the
(public member function)

© cppreference.com Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0. https://en.cppreference.com/w/cpp/container/vector/assign

  • C++ Standard Library - Home
  • C++ Library - <cctype> (ctype.h)
  • C++ Library - <cerrno> (errno.h)
  • C++ Library - <cfenv> (fenv.h)
  • C++ Library - <cfloat> (float.h)
  • C++ Library - <cinttypes> (inttypes.h)
  • C++ Library - <climits> (limits.h)
  • C++ Library - <clocale> (locale.h)
  • C++ Library - <cmath> (math.h)
  • C++ Library - <csignal> (signal.h)
  • C++ Library - <cstdarg> (stdarg.h)
  • C++ Library - <cstddef> (stddef.h)
  • C++ Library - <cstdio> (stdio.h)
  • C++ Library - <cstdint> (stdint.h)
  • C++ Library - <cstdlib> (stdlib.h)
  • C++ Library - <cstring> (string.h)
  • C++ Library - <ctime> (time.h)
  • C++ Library - <cwchar> (wchar.h)
  • C++ Library - <cwctype> (wctype.h)
  • C++ Library - <complex>
  • C++ Library - <initializer_list>
  • C++ Library - <iterator>
  • C++ Library - <memory>
  • C++ Library - <string>
  • C++ Library - <valarray>
  • C++ Library - <algorithm>
  • C++ Library - <array>
  • C++ Library - <bitset>
  • C++ Library - <deque>
  • C++ Library - <forward_list>
  • C++ Library - <list>
  • C++ Library - <map>
  • C++ Library - <queue>
  • C++ Library - <set>
  • C++ Library - <stack>
  • C++ Library - <unordered_map>
  • C++ Library - <unordered_set>
  • C++ Library - <vector>

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

C++ <vector> - assign() Function

The C++ vector::assign function is used to assign new values to the vector, replacing its old values, and modifying its size if necessary.

Specify the starting position of InputIterator. The range used by InputIterator is [first,last).
Specify the last position of InputIterator. The range used by InputIterator is [first,last).
Specify new size of the vector.
Specify the value to fill the vector with. Each of the vector will be initialized to a copy of this value.
Specify the initializer_list object.

Return Value

Time complexity.

Linear i.e, Θ(n)

In the example below, the vector::assign function is used to assign new values to the given vector, replacing its old values.

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

<vector>

Std:: vector ::assign.

range (1)
fill (2)
range (1)
fill (2)
initializer list (3)

Return value

main () { std::vector< > first; std::vector< > second; std::vector< > third; first.assign (7,100); std::vector< >::iterator it; it=first.begin()+1; second.assign (it,first.end()-1); myints[] = {1776,7,4}; third.assign (myints,myints+3); std::cout << << (first.size()) << ; std::cout << << (second.size()) << ; std::cout << << (third.size()) << ; 0; }

Iterator validity

Exception safety.

  • Information
  • <cassert> (assert.h)
  • <cctype> (ctype.h)
  • <cerrno> (errno.h)
  • <cfenv> (fenv.h)
  • <cfloat> (float.h)
  • <cinttypes> (inttypes.h)
  • <ciso646> (iso646.h)
  • <climits> (limits.h)
  • <clocale> (locale.h)
  • <cmath> (math.h)
  • <csetjmp> (setjmp.h)
  • <csignal> (signal.h)
  • <cstdarg> (stdarg.h)
  • <cstdbool> (stdbool.h)
  • <cstddef> (stddef.h)
  • <cstdint> (stdint.h)
  • <cstdio> (stdio.h)
  • <cstdlib> (stdlib.h)
  • <cstring> (string.h)
  • <ctgmath> (tgmath.h)
  • <ctime> (time.h)
  • <cuchar> (uchar.h)
  • <cwchar> (wchar.h)
  • <cwctype> (wctype.h)

Containers:

  • <array>
  • <deque>
  • <forward_list>
  • <list>
  • <map>
  • <queue>
  • <set>
  • <stack>
  • <unordered_map>
  • <unordered_set>

Input/Output:

  • <fstream>
  • <iomanip>
  • <ios>
  • <iosfwd>
  • <iostream>
  • <istream>
  • <ostream>
  • <sstream>
  • <streambuf>

Multi-threading:

  • <atomic>
  • <condition_variable>
  • <future>
  • <mutex>
  • <thread>
  • <algorithm>
  • <bitset>
  • <chrono>
  • <codecvt>
  • <complex>
  • <exception>
  • <functional>
  • <initializer_list>
  • <iterator>
  • <limits>
  • <locale>
  • <memory>
  • <new>
  • <numeric>
  • <random>
  • <ratio>
  • <regex>
  • <stdexcept>
  • <string>
  • <system_error>
  • <tuple>
  • <typeindex>
  • <typeinfo>
  • <type_traits>
  • <utility>
  • <valarray>
  • vector<bool>
  • vector::vector
  • vector::~vector

member functions:

  • vector::assign
  • vector::back
  • vector::begin
  • vector::capacity
  • vector::cbegin
  • vector::cend
  • vector::clear
  • vector::crbegin
  • vector::crend
  • vector::data
  • vector::emplace
  • vector::emplace_back
  • vector::empty
  • vector::end
  • vector::erase
  • vector::front
  • vector::get_allocator
  • vector::insert
  • vector::max_size
  • vector::operator=
  • vector::operator[]
  • vector::pop_back
  • vector::push_back
  • vector::rbegin
  • vector::rend
  • vector::reserve
  • vector::resize
  • vector::shrink_to_fit
  • vector::size
  • vector::swap

non-member overloads:

  • relational operators (vector)
  • swap (vector)

cppreference.com

Std::vector<t,allocator>:: vector.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)

vector::cbegin (C++11)
vector::cend (C++11)
vector::crbegin (C++11)
vector::crend (C++11)
)

operator!=operator<operator>operator<=operator>=operator<=> (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
erase_if(std::vector) (C++20)




(1)
); (until C++17)
) noexcept(noexcept(Allocator())); (since C++17)
(constexpr since C++20)
(2)
vector( const Allocator& alloc ); (until C++17)
vector( const Allocator& alloc ) noexcept; (since C++17)
(constexpr since C++20)
(3)
vector( size_type count,

                 const T& value = T(),

                 const Allocator& alloc = Allocator() );
(until C++11)
size_type count,

        const T& value,

        const Allocator& alloc = Allocator() );
(since C++11)
(constexpr since C++20)
(4)
vector( size_type count ); (since C++11)
(until C++14)
vector( size_type count,
                 const Allocator& alloc = Allocator() );
(since C++14)
< class InputIt >

vector( InputIt first, InputIt last,

        const Allocator& alloc = Allocator() );
(5) (constexpr since C++20)
const vector& other ); (6) (constexpr since C++20)
const vector& other, const Allocator& alloc ); (7) (since C++11)
(constexpr since C++20)
vector&& other ); (8) (since C++11)
(noexcept since C++17)
(constexpr since C++20)
vector&& other, const Allocator& alloc ); (9) (since C++11)
(constexpr since C++20)
<T> init,
        const Allocator& alloc = Allocator() );
(10) (since C++11)
(constexpr since C++20)
template< <T> R >

constexpr vector( , R&& rg,

                  const Allocator& alloc = Allocator() );
(11) (since C++23)

Constructs a new container from a variety of data sources, optionally using a user supplied allocator alloc .

This constructor has the same effect as vector(static_cast<size_type>(first), static_cast<value_type>(last), a) if is an integral type.

(until C++11)

This overload participates in overload resolution only if satisfies , to avoid ambiguity with the overload (3).

(since C++11)

The allocator is obtained as if by calling <allocator_type>::select_on_container_copy_construction(
    other.get_allocator()).

(since C++11)

During , only the first argument contributes to the deduction of the container's template parameter.

(since C++23)
Parameters Complexity Exceptions Notes Example Defect reports See also

[ edit ] Parameters

alloc - allocator to use for all memory allocations of this container
count - the size of the container
value - the value to initialize elements of the container with
first, last - the range first last to copy the elements from
other - another container to be used as source to initialize the elements of the container with
init - initializer list to initialize the elements of the container with
rg - a , that is, an whose elements are convertible to

[ edit ] Complexity

  • If first and last are both forward, bidirectional or random-access iterators,
  • The copy constructor of T is only called N   times, and
  • No reallocation occurs.
  • Otherwise ( first and last are just input iterators),
  • The copy constructor of T is called O(N) times, and
  • Reallocation occurs O(log N) times.
  • If R models ranges::forward_range or ranges::sized_range ,
  • Initializes exactly N elements from the result of dereferencing successive iterators of rg , and
  • Otherwise ( R models input range),
  • The copy or move constructor of T is called O(N) times, and

[ edit ] Exceptions

Calls to Allocator :: allocate may throw.

[ edit ] Notes

After container move construction (overload (8) ), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in * this . The current standard makes this guarantee via the blanket statement in [container.reqmts]/67 , and a more direct guarantee is under consideration via LWG issue 2321 .

The overload (4) zeroes out elements of non-class types such as int , which is different from the behavior of new[] , which leaves them uninitialized. To match the behavior of new [ ] , a custom Allocator::construct can be provided which leaves such elements uninitialized.

Note that the presence of list-initializing constructor (10) means list initialization and direct initialization do different things:

macro Value Std Feature
202202L (C++23) construction and insertion; overload ( )

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++98 overload (5) allowed up to 2N  copy
constructor calls in the input iterator case
changed to O(N) calls
C++98 for overload (4), the elements in the container were default constructed they are value-initialized
C++11 the default constructor is explicit made non-explicit

[ edit ] See also

assigns values to the container
(public member function)
assigns values to the container
(public member function)
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 5 November 2023, at 12:01.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

vector class

  • 8 contributors

The C++ Standard Library vector class is a class template for sequence containers. A vector stores elements of a given type in a linear arrangement, and allows fast random access to any element. A vector is the preferred container for a sequence when random-access performance is at a premium.

Type The element data type to be stored in the vector

Allocator The type that represents the stored allocator object that encapsulates details about the vector's allocation and deallocation of memory. This argument is optional and the default value is allocator<Type> .

Vectors allow constant time insertions and deletions at the end of the sequence. Inserting or deleting elements in the middle of a vector requires linear time. The deque class container is faster at insertions and deletions at the beginning and end of a sequence. The list class container is faster at insertions and deletions at any location within a sequence.

Vector reallocation occurs when a member function must increase the sequence contained in the vector object beyond its current storage capacity. Other insertions and erasures may alter various storage addresses within the sequence. In all such cases, iterators or references that point at altered portions of the sequence become invalid. If no reallocation happens, only iterators and references before the insertion/deletion point remain valid.

The vector<bool> class is a full specialization of the class template vector for elements of type bool . It has an allocator for the underlying type used by the specialization.

The vector<bool> reference class is a nested class whose objects can provide references to elements (single bits) within a vector<bool> object.

Constructors

Name Description
Constructs a vector of a specific size or with elements of a specific value or with a specific or as a copy of some other vector.
Name Description
(#allocator_type) A type that represents the class for the vector object.
A type that provides a random-access iterator that can read a element in a vector.
A type that provides a pointer to a element in a vector.
A type that provides a reference to a element stored in a vector. It's used for reading and doing operations.
A type that provides a random-access iterator that can read any element in the vector.
A type that provides the difference between the addresses of two elements in a vector.
A type that provides a random-access iterator that can read or modify any element in a vector.
A type that provides a pointer to an element in a vector.
A type that provides a reference to an element stored in a vector.
A type that provides a random-access iterator that can read or modify any element in a reversed vector.
A type that counts the number of elements in a vector.
A type that represents the data type stored in a vector.
Name Description
Erases a vector and copies the specified elements to the empty vector.
Returns a reference to the element at a specified location in the vector.
Returns a reference to the last element of the vector.
Returns a random-access iterator to the first element in the vector.
Returns the number of elements that the vector could contain without allocating more storage.
Returns a random-access const iterator to the first element in the vector.
Returns a random-access const iterator that points just beyond the end of the vector.
Returns a const iterator to the first element in a reversed vector.
Returns a const iterator to the end of a reversed vector.
Erases the elements of the vector.
Returns a pointer to the first element in the vector.
Inserts an element constructed in place into the vector at a specified position.
Adds an element constructed in place to the end of the vector.
Tests if the vector container is empty.
Returns a random-access iterator that points to the end of the vector.
Removes an element or a range of elements in a vector from specified positions.
Returns a reference to the first element in a vector.
Returns an object to the class used by a vector.
Inserts an element or many elements into the vector at a specified position.
Returns the maximum length of the vector.
Deletes the element at the end of the vector.
Add an element to the end of the vector.
Returns an iterator to the first element in a reversed vector.
Returns an iterator to the end of a reversed vector.
Reserves a minimum length of storage for a vector object.
Specifies a new size for a vector.
Discards excess capacity.
Returns the number of elements in the vector.
Exchanges the elements of two vectors.
Name Description
Returns a reference to the vector element at a specified position.
Replaces the elements of the vector with a copy of another vector.

allocator_type

A type that represents the allocator class for the vector object.

allocator_type is a synonym for the template parameter Allocator .

See the example for get_allocator for an example that uses allocator_type .

Erases a vector and copies the specified elements to the empty vector.

first Position of the first element in the range of elements to be copied.

last Position of the first element beyond the range of elements to be copied.

count The number of copies of an element being inserted into the vector.

value The value of the element being inserted into the vector.

init_list The initializer_list containing the elements to insert.

First, assign erases any existing elements in a vector. Then, assign either inserts a specified range of elements from the original vector into a vector, or it inserts copies of a new specified value element into a vector.

Returns a reference to the element at a specified location in the vector.

position The subscript or position number of the element to reference in the vector.

Return value

A reference to the element subscripted in the argument. If position is greater than the size of the vector, at throws an exception.

If the return value of at is assigned to a const_reference , the vector object can't be modified. If the return value of at is assigned to a reference , the vector object can be modified.

Returns a reference to the last element of the vector.

The last element of the vector. If the vector is empty, the return value is undefined.

If the return value of back is assigned to a const_reference , the vector object can't be modified. If the return value of back is assigned to a reference , the vector object can be modified.

When compiled by using _ITERATOR_DEBUG_LEVEL defined as 1 or 2, a runtime error occurs if you attempt to access an element in an empty vector. For more information, see Checked iterators .

Returns a random-access iterator to the first element in the vector.

A random-access iterator addressing the first element in the vector or to the location succeeding an empty vector . Always compare the value returned with vector::end to ensure it's valid.

If the return value of begin is assigned to a vector::const_iterator , the vector object can't be modified. If the return value of begin is assigned to an vector::iterator , the vector object can be modified.

Returns the number of elements that the vector could contain without allocating more storage.

The current length of storage allocated for the vector.

The member function resize will be more efficient if sufficient memory is allocated to accommodate it. Use the member function reserve to specify the amount of memory allocated.

Returns a const iterator that addresses the first element in the range.

A const random-access iterator that points at the first element of the range, or the location just beyond the end of an empty range (for an empty range, cbegin() == cend() ).

With the return value of cbegin , the elements in the range can't be modified.

You can use this member function in place of the begin() member function to guarantee that the return value is const_iterator . Typically, it's used in with the auto type deduction keyword, as shown in the following example. In the example, consider Container to be a modifiable (non- const ) container of any kind that supports begin() and cbegin() .

Returns a const past-the-end iterator that points to the element following the last element of the vector.

A const past-the-end iterator for the vector. It points to the element following the last element of the vector. That element is a placeholder and shouldn't be dereferenced. Only use it for comparisons. If the vector is empty, then vector::cend() == vector::cbegin() .

cend is used to test whether an iterator has passed the end of its range.

You can use this member function in place of the end() member function to guarantee that the return value is const_iterator . Typically, it's used with the auto type deduction keyword, as shown in the following example. In the example, consider Container to be a modifiable (non- const ) container of any kind that supports end() and cend() .

The value returned by cend shouldn't be dereferenced. Only use it for comparisons.

Erases the elements of the vector.

const_iterator

A type that provides a random-access iterator that can read a const element in a vector.

A type const_iterator can't be used to modify the value of an element.

See the example for back for an example that uses const_iterator .

const_pointer

A type that provides a pointer to a const element in a vector.

A type const_pointer can't be used to modify the value of an element.

An iterator is more commonly used to access a vector element.

const_reference

A type that provides a reference to a const element stored in a vector. It's used for reading and doing const operations.

A type const_reference can't be used to modify the value of an element.

const_reverse_iterator

A type that provides a random-access iterator that can read any const element in the vector.

A type const_reverse_iterator can't modify the value of an element and is used to iterate through the vector in reverse.

See rbegin for an example of how to declare and use an iterator.

Returns a const iterator to the first element in a reversed vector.

A const reverse random-access iterator addressing the first element in a reversed vector or addressing what had been the last element in the unreversed vector .

With the return value of crbegin , the vector object can't be modified.

Returns a const past-the-end reverse iterator that points to the element following the last element of the reversed vector.

A const reverse past-the-end iterator for the reversed vector. It points to the element following the last element of the reversed vector, which is the same as the element before the first element of the non-reversed vector. That element is a placeholder and shouldn't be dereferenced. Only use it for comparisons.

crend is used with a reversed vector just as vector::cend is used with a vector .

With the return value of crend (suitably decremented), the vector object can't be modified.

crend can be used to test to whether a reverse iterator has reached the end of its vector .

The value returned by crend shouldn't be dereferenced. Only use it for comparisons.

Returns a pointer to the first element in the vector.

A pointer to the first element in the vector or to the location succeeding an empty vector .

difference_type

A type that provides the difference between two iterators that refer to elements within the same vector.

A difference_type can also be described as the number of elements between two pointers, because a pointer to an element contains its address.

Inserts an element constructed in place into the vector at a specified position.

position The position in the vector where the first element is inserted.

args Constructor arguments. The function infers which constructor overload to invoke based on the arguments provided.

The function returns an iterator that points to the position where the new element was inserted into the vector .

Any insertion operation can be expensive, see vector class for a discussion of vector performance.

emplace_back

Adds an element constructed in place to the end of the vector.

Tests if the vector is empty.

true if the vector is empty; false if the vector isn't empty.

Returns a past-the-end iterator that points to the element following the last element of the vector.

A past-the-end iterator for the vector. It points to the element following the last element of the vector. That element is a placeholder and shouldn't be dereferenced. Only use it for comparisons. If the vector is empty, then vector::end() == vector::begin() .

If the return value of end is assigned to a variable of type const_iterator , the vector object can't be modified. If the return value of end is assigned to a variable of type iterator , the vector object can be modified.

Removes an element or a range of elements in a vector from specified positions.

position Position of the element to be removed from the vector.

first Position of the first element removed from the vector.

last Position just beyond the last element removed from the vector.

An iterator that designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists.

Returns a reference to the first element in a vector.

A reference to the first element in the vector object. If the vector is empty, the return is undefined.

If the return value of front is assigned to a const_reference , the vector object can't be modified. If the return value of front is assigned to a reference , the vector object can be modified.

get_allocator

Returns a copy of the allocator object used to construct the vector.

The allocator used by the vector.

Allocators for the vector class specify how the class manages storage. The default allocators supplied with C++ Standard Library container classes are sufficient for most programming needs. Writing and using your own allocator class is an advanced C++ feature.

Inserts an element, or many elements, or a range of elements into the vector at a specified position.

count The number of elements being inserted into the vector.

first The position of the first element in the range of elements to be copied.

last The position of the first element beyond the range of elements to be copied.

The first two insert functions return an iterator that points to the position where the new element was inserted into the vector.

As a precondition, first and last must not be iterators into the vector, or the behavior is undefined. Any insertion operation can be expensive, see vector class for a discussion of vector performance.

A type that provides a random-access iterator that can read or modify any element in a vector.

A type iterator can be used to modify the value of an element.

See the example for begin .

Returns the maximum length of the vector.

The maximum possible length of the vector.

Returns a reference to the vector element at a specified position.

position The position of the vector element.

If the position specified is greater than or equal to the size of the container, the result is undefined.

If the return value of operator[] is assigned to a const_reference , the vector object can't be modified. If the return value of operator[] is assigned to a reference, the vector object can be modified.

When compiled by using _ITERATOR_DEBUG_LEVEL defined as 1 or 2, a runtime error occurs if you attempt to access an element outside the bounds of the vector. For more information, see Checked iterators .

Replaces the elements of the vector with a copy of another vector.

right The vector being copied into the vector .

After erasing any existing elements in a vector , operator= either copies or moves the contents of right into the vector .

A type that provides a pointer to an element in a vector.

A type pointer can be used to modify the value of an element.

Deletes the element at the end of the vector.

For a code example, see vector::push_back() .

Adds an element to the end of the vector.

value The value to assign to the element added to the end of the vector.

Returns an iterator to the first element in a reversed vector.

A reverse random-access iterator addressing the first element in a reversed vector or addressing what had been the last element in the unreversed vector.

If the return value of rbegin is assigned to a const_reverse_iterator , the vector object can't be modified. If the return value of rbegin is assigned to a reverse_iterator , the vector object can be modified.

A type that provides a reference to an element stored in a vector.

See at for an example of how to use reference in the vector class.

Returns a past-the-end reverse iterator that points to the element following the last element of the reversed vector.

A reverse past-the-end iterator for the reversed vector. It points to the element following the last element of the reversed vector, which is the same as the element before the first element of the non-reversed vector. That element is a placeholder and shouldn't be dereferenced. Only use it for comparisons.

rend is used with a reversed vector just as end is used with a vector.

If the return value of rend is assigned to a const_reverse_iterator , then the vector object can't be modified. If the return value of rend is assigned to a reverse_iterator , then the vector object can be modified.

rend can be used to test to whether a reverse iterator has reached the end of its vector.

The value returned by rend shouldn't be dereferenced. Only use it for comparisons.

Reserves a minimum length of storage for a vector object, allocating space if necessary.

count The minimum length of storage to be allocated for the vector.

Specifies a new size for a vector.

new_size The new size of the vector.

value The initialization value of new elements added to the vector if the new size is larger that the original size. If the value is omitted, the new objects use their default constructor.

If the container's size is less than the requested size, new_size , resize adds elements to the vector until it reaches the requested size. When the container's size is larger than the requested size, resize deletes the elements closest to the end of the container until it reaches the size new_size . No action is taken if the present size of the container is the same as the requested size.

size reflects the current size of the vector.

reverse_iterator

A type that provides a random-access iterator that can read or modify any element in a reversed vector.

A type reverse_iterator is used to iterate through the vector in reverse.

See the example for rbegin .

shrink_to_fit

Discards excess capacity.

Returns the number of elements in the vector.

The current length of the vector.

A type that counts the number of elements in a vector.

See the example for capacity .

Exchanges the elements of two vectors.

right A vector providing the elements to be swapped. Or, a vector whose elements are to be exchanged with the elements in the vector left .

left A vector whose elements are to be exchanged with the elements in the vector right .

A type that represents the data type stored in a vector.

value_type is a synonym for the template parameter Type .

Constructs a vector. Overloads construct a vector of a specific size, or with elements of a specific value. Or, as a copy of all or part of some other vector. Some overloads also allow you to specify the allocator to use.

allocator The allocator class to use with this object. get_allocator returns the allocator class for the object.

count The number of elements in the constructed vector.

value The value of the elements in the constructed vector.

source The vector of which the constructed vector is to be a copy.

init_list The initializer_list containing the elements to copy.

All constructors store an allocator object ( allocator ) and initialize the vector.

The first two constructors specify an empty initial vector. The second constructor explicitly specifies the allocator type ( allocator ) to use.

The third constructor specifies a repetition of a specified number ( count ) of elements of the default value for class Type .

The fourth and fifth constructors specify a repetition of ( count ) elements of value value .

The sixth constructor specifies a copy of the vector source .

The seventh constructor moves the vector source .

The eighth constructor uses an initializer_list to specify the elements.

The ninth and tenth constructors copy the range [ first , last ) of a vector.

Thread Safety in the C++ Standard Library C++ Standard Library Reference

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators

Vector in C++ STL

  • 7 ways to Initialize Vector in C++

Commonly Used Methods

  • vector::begin() and vector::end() in C++ STL
  • vector::empty() and vector::size() in C++ STL
  • vector::operator= and vector::operator[ ] in C++ STL
  • vector::front() and vector::back() in C++ STL
  • vector::push_back() and vector::pop_back() in C++ STL
  • vector insert() Function in C++ STL
  • vector emplace() function in C++ STL
  • vector :: assign() in C++ STL
  • vector erase() and clear() in C++

Other Member Methods

  • vector max_size() function in C++ STL
  • vector capacity() function in C++ STL
  • vector rbegin() and rend() function in C++ STL
  • vector :: cbegin() and vector :: cend() in C++ STL
  • vector::crend() & vector::crbegin() with example
  • vector : : resize() in C++ STL
  • vector shrink_to_fit() function in C++ STL
  • Using std::vector::reserve whenever possible
  • vector data() function in C++ STL
  • 2D Vector In C++ With User Defined Size
  • Passing Vector to a Function in C++
  • How does a vector work in C++?
  • How to implement our own Vector Class in C++?
  • Advantages of vector over array in C++

Common Vector Programs

  • Sorting a vector in C++
  • How to reverse a Vector using STL in C++?
  • How to find the minimum and maximum element of a Vector using STL in C++?
  • How to find index of a given element in a Vector in C++

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes the array may need to be extended. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.

What is std::vector in C++?

std::vector in C++ is the class template that contains the vector container and its member functions. It is defined inside the <vector> header file. The member functions of the std::vector class provide various functionalities to vector containers.

Syntax to Declare Vector in C++

where the data type is the type of data of each element of the vector. You can remove the std:: if you have already used the std namespace.

Initialization of Vector in C++

We can initialize a vector in the following ways:

1. Initialization Using List

This initialization is done with a declaration. Here, we pass the list of elements to the vector constructor to create a vector with the specified elements.

2. Initialization With a Single Value

This initialization is also done with declaration. Here, we specify the size of the vector and then initialize every element of the vector with the value.

3. Initialization From Another Vector

This initialization is used to create a vector that is an exact copy of other_vec.

Some commonly used member functions of std::vector class are written below:

  • begin() – Returns an iterator pointing to the first element in the vector
  • end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector
  • rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
  • rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
  • cbegin() – Returns a constant iterator pointing to the first element in the vector.
  • cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
  • crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
  • crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
               
  • size() – Returns the number of elements in the vector.
  • max_size() – Returns the maximum number of elements that the vector can hold.
  • capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.
  • resize(n) – Resizes the container so that it contains ‘n’ elements.
  • empty() – Returns whether the container is empty.
  • shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
  • reserve() – Requests that the vector capacity be at least enough to contain n elements.
                 

Element access

  • reference operator [g] – Returns a reference to the element at position ‘g’ in the vector
  • at(g) – Returns a reference to the element at position ‘g’ in the vector
  • front() – Returns a reference to the first element in the vector
  • back() – Returns a reference to the last element in the vector
  • data() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
               
  • assign() – It assigns new value to the vector elements by replacing old ones
  • push_back() – It push the elements into a vector from the back
  • pop_back() – It is used to pop or remove elements from a vector from the back.
  • insert() – It inserts new elements before the element at the specified position
  • erase() – It is used to remove elements from a container from the specified position or range.
  • swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.
  • clear() – It is used to remove all the elements of the vector container
  • emplace() – It extends the container by inserting new element at position
  • emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
                                     

The time complexity for doing various operations on vectors is-

  • Random access – constant O(1)
  • Insertion or removal of elements at the end – constant O(1)
  • Insertion or removal of elements – linear in the distance to the end of the vector O(N)
  • Knowing the size – constant O(1)
  • Resizing the vector- Linear O(N)  

All Member Functions of std::vector

Following is the list of all member functions of std::vector class in C++:

Vector Function

Description

Adds an element to the end of the vector.

Removes the last element of the vector.

Returns the number of elements in the vector.

Returns the maximum number of elements that the vector can hold.

Changes the size of the vector.

Checks if the vector is empty.

Accesses the element at a specific position.

Accesses the element at a specific position, with bounds checking.

Accesses the first element of the vector.

Accesses the last element of the vector.

Returns an iterator pointing to the first element of the vector.

Returns an iterator pointing to the past-the-end element of the vector.

Returns a reverse iterator pointing to the last element of the vector.

Returns a reverse iterator pointing to the element preceding the first element of the vector.

Returns const_iterator to beginning 

Returns const_iterator to end

Returns const_reverse_iterator to reverse beginning

Returns const_reverse_iterator to reverse end

Inserts elements at a specific position in the vector.

Removes elements from a specific position or range in the vector.

Swaps the contents of the vector with those of another vector.

Removes all elements from the vector.

Constructs and inserts an element in the vector.

Constructs and inserts an element at the end of the vector.

Assigns new values to the vector elements by replacing old ones.

Returns the size of the storage space currently allocated to the vector.

Requests that the vector capacity be at least enough to contain a specified number of elements.

Reduces memory usage by freeing unused space.

Returns a direct pointer to the memory array used internally by the vector to store its owned elements. 

Returns a copy of the allocator object associated with the vector.
  • How to Check if a Vector Contains a Given Element in C++?

Please Login to comment...

Similar reads.

  • cpp-containers-library

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • <cassert> (assert.h)
  • <cctype> (ctype.h)
  • <cerrno> (errno.h)
  • C++11 <cfenv> (fenv.h)
  • <cfloat> (float.h)
  • C++11 <cinttypes> (inttypes.h)
  • <ciso646> (iso646.h)
  • <climits> (limits.h)
  • <clocale> (locale.h)
  • <cmath> (math.h)
  • <csetjmp> (setjmp.h)
  • <csignal> (signal.h)
  • <cstdarg> (stdarg.h)
  • C++11 <cstdbool> (stdbool.h)
  • <cstddef> (stddef.h)
  • C++11 <cstdint> (stdint.h)
  • <cstdio> (stdio.h)
  • <cstdlib> (stdlib.h)
  • <cstring> (string.h)
  • C++11 <ctgmath> (tgmath.h)
  • <ctime> (time.h)
  • C++11 <cuchar> (uchar.h)
  • <cwchar> (wchar.h)
  • <cwctype> (wctype.h)

Containers:

  • C++11 <array>
  • <deque>
  • C++11 <forward_list>
  • <list>
  • <map>
  • <queue>
  • <set>
  • <stack>
  • C++11 <unordered_map>
  • C++11 <unordered_set>
  • <vector>

Input/Output:

  • <fstream>
  • <iomanip>
  • <ios>
  • <iosfwd>
  • <iostream>
  • <istream>
  • <ostream>
  • <sstream>
  • <streambuf>

Multi-threading:

  • C++11 <atomic>
  • C++11 <condition_variable>
  • C++11 <future>
  • C++11 <mutex>
  • C++11 <thread>
  • <algorithm>
  • <bitset>
  • C++11 <chrono>
  • C++11 <codecvt>
  • <complex>
  • <exception>
  • <functional>
  • C++11 <initializer_list>
  • <iterator>
  • <limits>
  • <locale>
  • <memory>
  • <new>
  • <numeric>
  • C++11 <random>
  • C++11 <ratio>
  • C++11 <regex>
  • <stdexcept>
  • <string>
  • C++11 <system_error>
  • C++11 <tuple>
  • C++11 <type_traits>
  • C++11 <typeindex>
  • <typeinfo>
  • <utility>
  • <valarray>
  • list::~list

member functions

  • list::assign
  • list::begin
  • C++11 list::cbegin
  • C++11 list::cend
  • list::clear
  • C++11 list::crbegin
  • C++11 list::crend
  • C++11 list::emplace
  • C++11 list::emplace_back
  • C++11 list::emplace_front
  • list::empty
  • list::erase
  • list::front
  • list::get_allocator
  • list::insert
  • list::max_size
  • list::merge
  • list::operator=
  • list::pop_back
  • list::pop_front
  • list::push_back
  • list::push_front
  • list::rbegin
  • list::remove
  • list::remove_if
  • list::resize
  • list::reverse
  • list::splice
  • list::unique

non-member overloads

  • relational operators (list)
  • swap (list)

std:: list ::assign

range (1)
fill (2)
range (1)
fill (2)
initializer list (3)

Return value

main () { std::list< > first; std::list< > second; first.assign (7,100); second.assign (first.begin(),first.end()); myints[]={1776,7,4}; first.assign (myints,myints+3); std::cout << << (first.size()) << ; std::cout << << (second.size()) << ; 0; }

Iterator validity

Exception safety.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

stl vector assign vs insert

I understand the semantics of the 2 operations , assign- erases before replacing with supplied values. insert - inserts values at specified location(allocates new memory if necessary).

Apart from this is there any reason to preffer one over the other? Or to put it another way, is there any reason to use assign instead of insert.

Pradyot's user avatar

  • 5 Maybe you can rescue this question by asking this instead: "Assign vs insert on empty STL vector , any difference?" –  Emile Cormier Commented Jan 22, 2010 at 17:59
  • Fair enough. Thats what i had in mind. –  Pradyot Commented Jan 22, 2010 at 18:01
  • 12 years and still not revised. tsk tsk tsk –  Max Power Commented Jul 7, 2022 at 19:26

4 Answers 4

assign and insert are only equivalent if the vector is empty to begin with. If the vector is already empty, then it's better to use assign , because insert would falsely hint to the reader that there are existing elements to be preserved.

Emile Cormier's user avatar

If you wish to invoke the semantics of assign , call assign - if you wish to invoke the semantics of insert , call insert. They aren't interchangeable.

As for calling them on an empty vector, the only difference is that you don't need to supply an iterator to insert at when you call assign . There may be a performance difference, but that's implementation specific and almost certainly negligable.

JoeG's user avatar

assign() will blow away anything that's already in the vector , then add the new elements. insert() doesn't touch any elements already in the vector .

Other than that, if the vector you are modifying starts out empty, there is little difference.

John Dibling's user avatar

insert() will insert the elements at a particular position. It can be a single value, or multiple values using first and last iterators. Its like inserting more elements in front of a position.

assign() will just assign the values starting at beginning till end as per input agruments "InputIterator first and InputIterator last ". This will remove all existing elements and instead populate the vector with new values as per range provided in its arguments.

Gurpreet Dhami's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ stl vector or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Should we burninate the [lib] tag?
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Drawing waves using tikz in latex
  • How do I pour *just* the right amount of plaster into these molds?
  • How to model an optimization problem with mutual exclusivity of two variables, without introducing integer variables?
  • adding *any* directive above Include negates HostName inside that included file
  • Could a transparent frequency-altering material be possible?
  • Is physics limited to smooth sets?
  • Algorithm to evaluate "connectedness" of a binary matrix
  • An alternative way to solve a classic problem of combinatorics
  • Do countries at war always treat each other's diplomats as personae non gratae?
  • Less ridiculous way to prove that an Ascii character compares equal with itself in Coq
  • "All due respect to jazz." - Does this mean the speaker likes it or dislikes it?
  • Why can't I conserve mass instead of moles and apply ratio in this problem?
  • How are "pursed" and "rounded" synonymous?
  • Can I tell a MILP solver to prefer solutions with fewer fractions?
  • Why was William Tyndale executed but nothing happened to Miles Coverdale?
  • How will the ISS be decommissioned?
  • Is there any instance of Sati practice described in Itihasa and Purana?
  • Why did Geordi have his visor replaced with ocular implants between Generations and First Contact?
  • Would a spaceport on Ceres make sense?
  • Tubeless tape width?
  • What kind of sequence is between an arithmetic and a geometric sequence?
  • Should mail addresses for logins be stored hashed to minimize impact of data loss?
  • what is the difference between prayer (προσευχῇ) and prayer also translated as supplication (δέησις) in Philippians 4:6?
  • What is the translation of misgendering in French?

vector assign list

IMAGES

  1. Vector::assign的使用_vector assign-CSDN博客

    vector assign list

  2. Checklist Images

    vector assign list

  3. List icon Royalty Free Vector Image

    vector assign list

  4. Portapapeles Lista De Verificación

    vector assign list

  5. The Output Is Five More Than Half The Input

    vector assign list

  6. Vector assign by Mitchell Heather

    vector assign list

VIDEO

  1. R Programming

  2. Vector

  3. Vector

  4. Vector

  5. Homemade projector hack

  6. Vector Manipulation

COMMENTS

  1. std::vector<T,Allocator>::assign

    std::vector<T,Allocator>:: assign. Replaces the contents of the container. 1) Replaces the contents with count copies of value value. 2) Replaces the contents with copies of those in the range [first,last). The behavior is undefined if either argument is an iterator into *this . This overload has the same effect as overload (1) if InputIt is an ...

  2. vector :: assign() in C++ STL

    The syntax for assigning values from an array or list: vectorname.assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned. Program 2: The program below shows how to assign values from an array or list

  3. vector

    Assign vector content Assigns new contents to the vector , replacing its current contents, and modifying its size accordingly. In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last , in the same order.

  4. vector<...>::assign() method

    std::vector assign () method. Replaces the contents of the container with the contents of another. (1) Replaces the contents with count copies of value value. (2) Replaces the contents with copies of those in the range [ first, last ).

  5. std::vector

    namespace pmr {. template<class T > using vector = std ::vector< T, std::pmr::polymorphic_allocator< T >>; } (2) (since C++17) 1)std::vector is a sequence container that encapsulates dynamic size arrays. 2)std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can ...

  6. C++ Vector Library

    The C++ function std::vector::assign () assign new values to the vector elements by replacing old ones. It modifies size of vector if necessary. If memory allocation happens allocation is allocated by internal allocator. New contents are the copies of values passed as initializer list, in the same order.

  7. std::vector::assign

    Replaces the contents of the container. 1) replaces the contents with count copies of value value. 2) replaces the contents with copies of those in the range [first, last). 3) replaces the contents with the elements from the initializer list ilist.

  8. std::vector<T,Allocator>::assign

    std::vector<T,Allocator>:: assign < cpp‎ | container‎ ... initializer list to copy the values from Complexity. 1) Linear in count. 2) Linear in distance between first and last. 3) Linear in ilist. size Example. The following code uses assign to add several characters to a std:: vector < char >:

  9. Std::vector::assign

    constexpr void assign( std::initializer_list<T> ilist ); (since C++20) Replaces the contents of the container. 1) Replaces the contents with count copies of value value. 2) Replaces the contents with copies of those in the range [first, last). The behavior is undefined if either argument is an iterator into *this.

  10. vector

    Instead, vector containers may allocate some extra storage to accommodate for possible growth, ... assign Assign vector content (public member function) push_back Add element at the end (public member function) pop_back Delete last element (public member function) insert

  11. C++ <vector> assign() Function

    The C++ vector::assign function is used to assign new values to the vector, replacing its old values, and modifying its size if necessary. Syntax. C++98; C++11 //range version template <class InputIterator> void assign (InputIterator first, InputIterator last); //fill version void assign (size_type n, const value_type& val);

  12. What's difference between those two std::vector's assign methods?

    +1 And note that .assign(beg,end) requires the arbitrary type T be emplace-constructible or move-insertible (the latter for std::vector<T> specifically when the iterator type does not meet forward iterator requirements). The requirements for the assignment operator are different; T must be copy-insertible and copy-assignable. Not that it matters much in the OP's case, but just to note that ...

  13. What is the difference between "vector::operator=" and "vector::assign"?

    1. Their return types differ: the operator returns the vector by reference, assign returns void. Technically, the spec for assignment from initializer_list says the elements are "assigned or destroyed ", while assign from initializer_list "replaces elements " ( Table 87 ), but that seems immaterial: actual implementations of one just call the ...

  14. vector::assign

    Assign vector content. Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly. C++98. C++11. In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order. In the fill version (2), the new contents are n ...

  15. std::vector<T,Allocator>::vector

    constexpr vector (std::from_range_t, R && rg, const Allocator& alloc = Allocator()); (11) (since C++23) Constructs a new container from a variety of data sources, optionally using a user supplied allocator alloc . 1) Default constructor. Constructs an empty container with a default-constructed allocator. 2) Constructs an empty container with ...

  16. vector class

    The value of the element being inserted into the vector. init_list The initializer_list containing the elements to insert. Remarks. First, assign erases any existing elements in a vector. Then, assign either inserts a specified range of elements from the original vector into a vector, or it inserts copies of a new specified value element into a ...

  17. Vector in C++ STL

    Syntax to Declare Vector in C++. std::vector<dataType> vectorName; where the data type is the type of data of each element of the vector. You can remove the std:: if you have already used the std namespace. Initialization of Vector in C++. We can initialize a vector in the following ways: 1. Initialization Using List.

  18. list

    In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order. In the fill version (2), the new contents are n elements, each initialized to a copy of val. In the initializer list version (3), the new contents are copies of the values passed as initializer list, in the same order.

  19. c++

    1. insert () will insert the elements at a particular position. It can be a single value, or multiple values using first and last iterators. Its like inserting more elements in front of a position. assign () will just assign the values starting at beginning till end as per input agruments "InputIterator first and InputIterator last ".