std::vector operator=

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

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

(1) Copy assignment operator. Replaces the contents with a copy of the contents of other .

If std::allocator_traits<Alloc>::propagate_on_container_copy_assignment::value is true , the allocator of *this is replaced by a copy of that of other.

If the allocator of *this after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements.

Otherwise, the memory owned by *this may be reused when possible.

In any case, the elements originally belong to *this may be either destroyed or replaced by element-wise copy-assignment.

(2) Move assignment operator. Replaces the contents with those of other using move semantics (i.e. the data in other is moved from other into this container).

other is in a valid but unspecified state afterwards.

If std::allocator_traits<Alloc>::propagate_on_container_move_assignment::value is true , the allocator of *this is replaced by a copy of that of other.

If it is false and the allocators of *this and other do not compare equal, *this cannot take ownership of the memory owned by other and must move-assign each element individually, allocating additional memory using its own allocator as needed.

In any case, all elements originally belong to *this are either destroyed or replaced by element-wise move-assignment.

(3) Replaces the contents with those identified by initializer list ilist .

Parameters ​

  • other - another container to use as data source
  • ilist - initializer list to use as data source

Return value ​

Complexity ​.

(1) Linear in the size of *this and other - O(size() + other.size(()) .

(2) Linear in the size of *this - O(size()) . If allocators do not compare equal and do not propagate, linear in the size of *this and other - O(size() + other.size()) .

(3) Linear in the size of *this and ilist - O(size() + ilist.size()) .

Exceptions ​

  • until C++17
  • (1, 2) May throw implementation-defined exceptions.
  • (3) Noexcept specification:

After container move assignment (overload (2) ), unless element-wise move assignment is forced by incompatible allocators, 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.requirements.general]/12 , and a more direct guarantee is under consideration via LWG 2321 .

  • Return value

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Booleans
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • C - Functions
  • C - Main Functions
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • 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

Assignment Operators in C

In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the " = " symbol, which is defined as a simple assignment operator in C.

In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per the ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed.

You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable, or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented Assignment Operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression "a += b" has the same effect of performing "a + b" first and then assigning the result back to the variable "a".

Run the code and check its output −

Similarly, the expression "a <<= b" has the same effect of performing "a << b" first and then assigning the result back to the variable "a".

Here is a C program that demonstrates the use of assignment operators in C −

When you compile and execute the above program, it will produce the following result −

To Continue Learning Please Login

  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
  • Vector in C++ STL
  • Initialize a vector in C++ (7 different ways)

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++

vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

The syntax for assigning constant values: 

Program 1: The program below shows how to assign constant values to a vector 

The syntax for assigning values from an array or list: 

Program 2: The program below shows how to assign values from an array or list 

The syntax for modifying values from a vector  

Program 3: The program below shows how to modify the vector 

Time Complexity – Linear O(N)

Syntax for assigning values with initializer list:

Program 4:The program below shows how to assign a vector with an initializer list.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • 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 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

IMAGES

  1. Assignment Operators in C

    vector assignment operator c

  2. Assignment Operators in C » PREP INSTA

    vector assignment operator c

  3. VECTOR OPERATORS

    vector assignment operator c

  4. Assignment Operator in C

    vector assignment operator c

  5. Assignment Operators in C++

    vector assignment operator c

  6. [100% Working Code]

    vector assignment operator c

VIDEO

  1. assignment Operator C Language in Telugu

  2. Augmented assignment operators in C

  3. Assignment Operator in C Programming

  4. Assignment Operator in C Programming

  5. Assignment Operator│C programming│Part# 15│Learn CSE Malayalam

  6. Fundamentals Pen Tool Vector Assignment

COMMENTS

  1. c++

    The assignment operator does this, as does vector::assign: v2.assign(v1.begin(), v1.end()); ... The invocation of std::copy may try to access items beyond the end of the destination vector. Use assignment. It's not your job to micro-optimize: that's the library writer's responsibility, and ultimately the compiler's responsibility. ...

  2. 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 ...

  3. std::vector<T,Allocator>::operator=

    1) Copy assignment operator. Replaces the contents with a copy of the contents of other . If std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value is true, the allocator of *this is replaced by a copy of other. If the allocator of *this after assignment would compare unequal to its old value, the old allocator is ...

  4. vector::operator= and vector::operator [ ] in C++ STL

    1. It is used to assign new contents to the container and replace its current contents. It is used to assign new contents to the container by replacing its current contents. 2. Its syntax is -: vector& operator= (const vector& x); Its syntax is -: vector& operator= (const vector& x); 3.

  5. c++

    Actually there are three assignment operators defined: vector& operator=( const vector& other ); vector& operator=( vector&& other ); vector& operator=( std::initializer_list<T> ilist ); Your suggestion vector& vector::operator=(vector other) uses the copy and swap idiom. That means, that when the operator is called, the original vector will be ...

  6. vector

    The copy assignment (1) copies all the elements from x into the container (with x preserving its contents). The move assignment (2) moves the elements of x into the container (x is left in an unspecified but valid state). The initializer list assignment (3) copies the elements of il into the container. The container preserves its current allocator, except if the allocator traits indicate that ...

  7. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  8. vector<...>::operator=

    std::vector operator=. Replaces the contents of the container with the contents of another. (1) Copy assignment operator. Replaces the contents with a copy of the contents of other. If std::allocator_traits<Alloc>::propagate_on_container_copy_assignment::value is true, the allocator of *this is replaced by a copy of that of other.

  9. vector

    Complexity Linear on initial and final sizes (destructions, constructions). Additionally, in the range version (1), if InputIterator is not at least of a forward iterator category (i.e., it is just an input iterator) the new capacity cannot be determined beforehand and the operation incurs in additional logarithmic complexity in the new size (reallocations while growing).

  10. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  11. vector

    Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this ...

  12. Copy assignment operator

    the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial. A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.

  13. Everything You Need To Know About The Copy Assignment Operator In C++

    Classes and Objects are part of object-oriented methods and typically provide features such as properties and methods. One of the great features of an object orientated language like C++ is a copy assignment operator that is used with operator= to create a new object from an existing one. In this post, we explain what a copy assignment operator is and its types in usage with some C++ examples.

  14. Assignment Operators in C

    Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=.

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

    vector:: assign () is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary. The syntax for assigning constant values: vectorname.assign(int size, int value) Parameters: size - number of values to be assigned.

  16. operator==,!=,<,<=,>,>=,<=>(std::vector)

    The relational operators are defined in terms of the element type's operator< . (until C++20) The relational operators are defined in terms of synth-three-way, which uses operator<=> if possible, or operator< otherwise. Notably, if the element does not itself provide operator<=>, but is implicitly convertible to a three-way comparable type ...

  17. Move assignment operator

    The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.. Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors ...

  18. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  19. c++

    The reason why is ill formed, is that the member functions of the class std::vector could call the assignment operator of its template argument, but in this case it's a constant type parameter "const int" which means it doesn't have an assignment operator ( it's none sense to assign to a const variable!!). the same behavior is observed with a ...