• Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

C++ (on Sea) Online

February 7-9

ISO C++ committee meeting

March 18-23, Tokyo, Japan

April 17-20, Bristol, UK

using std::cpp 2024

April 24-26, Leganes, Spain  

C++ Now 2024

May 7-12, Aspen, CO, USA

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

What is a reference?

An alias (an alternate name) for an object.

References are frequently used for pass-by-reference:

Here i and j are aliases for main’s x and y respectively. In other words, i is x — not a pointer to x , nor a copy of x , but x itself. Anything you do to i gets done to x , and vice versa. This includes taking the address of it. The values of &i and &x are identical.

That’s how you should think of references as a programmer. Now, at the risk of confusing you by giving you a different perspective, here’s how references are implemented. Underneath it all, a reference i to object x is typically the machine address of the object x . But when the programmer says i++ , the compiler generates code that increments x . In particular, the address bits that the compiler uses to find x are not changed. A C programmer will think of this as if you used the C style pass-by-pointer, with the syntactic variant of (1) moving the & from the caller into the callee, and (2) eliminating the * s. In other words, a C programmer will think of i as a macro for (*p) , where p is a pointer to x (e.g., the compiler automatically dereferences the underlying pointer; i++ is changed to (*p)++ ; i = 7 is automatically changed to *p = 7 ).

Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. It is neither a pointer to the object, nor a copy of the object. It is the object. There is no C++ syntax that lets you operate on the reference itself separate from the object to which it refers.

What happens if you assign to a reference?

You change the state of the referent (the referent is the object to which the reference refers).

Remember: the reference is the referent, so changing the reference changes the state of the referent. In compiler writer lingo, a reference is an “lvalue” (something that can appear on the left hand side of an assignment operator ).

What happens if you return a reference?

The function call can appear on the left hand side of an assignment operator .

This ability may seem strange at first. For example, no one thinks the expression f() = 7 makes sense. Yet, if a is an object of class Array , most people think that a[i] = 7 makes sense even though a[i] is really just a function call in disguise (it calls Array::operator[](int) , which is the subscript operator for class Array ).

What does object.method1().method2() mean?

It chains these method calls, which is why this is called method chaining .

The first thing that gets executed is object.method1() . This returns some object, which might be a reference to object (i.e., method1() might end with return *this; ), or it might be some other object. Let’s call the returned object objectB . Then objectB becomes the this object of method2() .

The most common use of method chaining is in the iostream library. E.g., cout << x << y works because cout << x is a function that returns cout .

A less common, but still rather slick, use for method chaining is in the Named Parameter Idiom .

How can you reseat a reference to make it refer to a different object?

You can’t separate the reference from the referent.

Unlike a pointer, once a reference is bound to an object, it can not be “reseated” to another object. The reference isn’t a separate object. It has no identity. Taking the address of a reference gives you the address of the referent. Remember: the reference is its referent.

In that sense, a reference is similar to a const pointer such as int* const p (as opposed to a pointer to const such as const int* p ). But please don’t confuse references with pointers; they’re very different from the programmer’s standpoint.

Why does C++ have both pointers and references?

C++ inherited pointers from C, so they couldn’t be removed without causing serious compatibility problems. References are useful for several things, but the direct reason they were introduced in C++ was to support operator overloading. For example:

More generally, if you want to have both the functionality of pointers and the functionality of references, you need either two different types (as in C++) or two different sets of operations on a single type. For example, with a single type you need both an operation to assign to the object referred to and an operation to assign to the reference/pointer. This can be done using separate operators (as in Simula). For example:

Alternatively, you could rely on type checking (overloading). For example:

When should I use references, and when should I use pointers?

Use references when you can, and pointers when you have to.

References are usually preferred over pointers whenever you don’t need “reseating” . This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside.

The exception to the above is where a function’s parameter or return value needs a “sentinel” reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the nullptr value this special significance ( references must always alias objects, not a dereferenced null pointer ).

Note: Old line C programmers sometimes don’t like references since they provide reference semantics that isn’t explicit in the caller’s code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.

What does it mean that a reference must refer to an object, not a dereferenced null pointer?

It means this is illegal:

NOTE: Please do not email us saying the above works on your particular version of your particular compiler. It’s still illegal. The C++ language, as defined by the C++ standard, says it’s illegal; that makes it illegal. The C++ standard does not require a diagnostic for this particular error, which means your particular compiler is not obliged to notice that p is nullptr or to give an error message, but it’s still illegal. The C++ language also does not require the compiler to generate code that would blow up at runtime. In fact, your particular version of your particular compiler may, or may not, generate code that you think makes sense if you do the above. But that’s the point: since the compiler is not required to generate sensible code, you don’t know what the compiler will do. So please do not email us saying your particular compiler generates good code; we don’t care. It’s still illegal. See the C++ standard for more, for example, C++ 2014 section 8.3.2 [dcl.ref] p5.

By way of example and not by way of limitation, some compilers do optimize nullptr tests since they “know” all references refer to real objects — that references are never (legally) a dereferenced nullptr . That can cause a compiler to optimize away the following test:

As stated above, this is just an example of the sort of thing your compiler might do based on the language rule that says a reference must refer to a valid object. Do not limit your thinking to the above example; the message of this FAQ is that the compiler is not required to do something sensible if you violate the rules. So don’t violate the rules.

Patient: “Doctor, doctor, my eye hurts when I poke it with a spoon.” Doctor: “Don’t poke it, then.”

What is a handle to an object? Is it a pointer? Is it a reference? Is it a pointer-to-a-pointer? What is it?

The term handle is used to mean any technique that lets you get to another object — a generalized pseudo-pointer. The term is (intentionally) ambiguous and vague.

Ambiguity is actually an asset in certain cases. For example, during early design you might not be ready to commit to a specific representation for the handles. You might not be sure whether you’ll want simple pointers vs. references vs. pointers-to-pointers vs. references-to-pointers vs. integer indices into an array vs. strings (or other key) that can be looked up in a hash-table (or other data structure) vs. database keys vs. some other technique. If you merely know that you’ll need some sort of thingy that will uniquely identify and get to an object, you call the thingy a Handle.

So if your ultimate goal is to enable a glop of code to uniquely identify/look-up a specific object of some class Fred , you need to pass a Fred handle into that glop of code. The handle might be a string that can be used as a key in some well-known lookup table (e.g., a key in a std::map<std::string,Fred> or a std::map<std::string,Fred*> ), or it might be an integer that would be an index into some well-known array (e.g., Fred* array = new Fred[maxNumFreds] ), or it might be a simple Fred* , or it might be something else.

Novices often think in terms of pointers, but in reality there are downside risks to using raw pointers. E.g., what if the Fred object needs to move? How do we know when it’s safe to delete the Fred objects? What if the Fred object needs to (temporarily) get serialized on disk? etc., etc. Most of the time we add more layers of indirection to manage situations like these. For example, the handles might be Fred** , where the pointed-to Fred* pointers are guaranteed to never move but when the Fred objects need to move, you just update the pointed-to Fred* pointers. Or you make the handle an integer then have the Fred objects (or pointers to the Fred objects) looked up in a table/array/whatever. Or whatever.

The point is that we use the word Handle when we don’t yet know the details of what we’re going to do.

Another time we use the word Handle is when we want to be vague about what we’ve already done (sometimes the term magic cookie is used for this as well, as in, “The software passes around a magic cookie that is used to uniquely identify and locate the appropriate Fred object”). The reason we (sometimes) want to be vague about what we’ve already done is to minimize the ripple effect if/when the specific details/representation of the handle change. E.g., if/when someone changes the handle from a string that is used in a lookup table to an integer that is looked up in an array, we don’t want to go and update a zillion lines of code.

To further ease maintenance if/when the details/representation of a handle changes (or to generally make the code easier to read/write), we often encapsulate the handle in a class. This class often overloads operators operator-> and operator* (since the handle acts like a pointer, it might as well look like a pointer).

Should I use call-by-value or call-by-reference?

(Note: This FAQ needs to be updated for C++11.)

That depends on what you are trying to achieve:

  • If you want to change the object passed, call by reference or use a pointer; e.g., void f(X&); or void f(X*); .
  • If you don’t want to change the object passed and it is big, call by const reference; e.g., void f(const X&); .
  • Otherwise, call by value; e.g. void f(X); .

What does “big” mean? Anything larger than a couple of words.

Why would you want to change an argument? Well, often we have to, but often we have an alternative: produce a new value. Consider:

For a reader, incr2() is likely easier to understand. That is, incr1() is more likely to lead to mistakes and errors. So, we should prefer the style that returns a new value over the one that modifies a value as long as the creation and copy of a new value isn’t expensive.

What if you do want to change the argument, should you use a pointer or use a reference? If passing “not an object” (e.g., a null pointer) is acceptable, using a pointer makes sense. One style is to use a pointer when you want to modify an object because in some contexts that makes it easier to spot that a modification is possible.

Note also that a call of a member function is essentially a call-by-reference on the object, so we often use member functions when we want to modify the value/state of an object.

Why is this not a reference?

Because this was introduced into C++ (really into C with Classes) before references were added. Also, Stroustrup chose this to follow Simula usage, rather than the (later) Smalltalk use of self .

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

  • <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>
  • vector<bool>
  • vector::~vector
  • vector::vector

member functions

  • vector::assign
  • vector::back
  • vector::begin
  • vector::capacity
  • C++11 vector::cbegin
  • C++11 vector::cend
  • vector::clear
  • C++11 vector::crbegin
  • C++11 vector::crend
  • C++11 vector::data
  • C++11 vector::emplace
  • C++11 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
  • C++11 vector::shrink_to_fit
  • vector::size
  • vector::swap

non-member overloads

  • relational operators (vector)
  • swap (vector)

std:: vector ::operator=

Return value, iterator validity, exception safety.

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 .

[ edit ] Parameters

[ 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

How to Pass Vector by Reference in C++

  • How to Pass Vector by Reference in C++

Use the vector<T> &arr Notation to Pass a Vector by Reference in C++

Use the const vector<t> &arr notation to pass a vector by reference in c++, use the vector<t>* arr notation to pass a vector by reference in c++, use std::reference_wrapper to pass a vector by reference in c++.

How to Pass Vector by Reference in C++

Passing vectors by reference in C++ is an optimization technique to enhance both performance and memory efficiency, especially when dealing with large datasets. This article explores several methods to achieve this, each offering its advantages based on specific use cases.

One effective way to pass vectors efficiently in C++ is by using the vector<T> &arr notation, allowing functions to operate directly on the original vector without creating unnecessary copies.

The vector<T> &arr notation indicates passing a reference to a vector of type T . The ampersand ( & ) denotes a reference, meaning the function receives the memory address of the original vector rather than a new copy.

This approach is beneficial as it avoids the overhead of duplicating the entire vector and enables modifications to the original vector within the function.

Code Example:

In the code example, the multiplyByTwo function takes a reference to a vector of integers ( vector<int> &arr ) as its parameter. Inside the function, a range-based for loop is used to iterate through each element of the vector, and each element is then multiplied by two.

The function returns a reference to the modified vector, allowing the changes to directly impact the original vector.

In the main function, a vector named arr is initialized with a sequence of integers from 1 to 10. The elements are displayed using the copy function along with an ostream_iterator to display the initial state of the vector.

The multiplyByTwo function is then called, passing the vector arr as an argument. The returned reference, assigned to arr_mult_by2 , holds the modified vector.

Following the function call, the program proceeds to display the modified vector using the same technique with the copy function and ostream_iterator . The output provides a clear illustration of the vector’s transformation.

The code emphasizes the efficiency gained by passing vectors by reference, as it eliminates the need for creating redundant copies of the entire vector. By directly manipulating the original vector within the function, both memory and processing resources are conserved.

This approach is particularly advantageous when dealing with large datasets, contributing to improved performance and code readability.

Another efficient vector manipulation method in C++ is the const vector<T> &arr notation. This notation, employing the const qualifier, ensures that the passed vector remains unaltered within the function scope.

The const vector<T> &arr notation signifies the passing of a constant reference to a vector of type T . The addition of the const keyword informs the compiler that the function won’t modify the vector it receives as an argument.

This not only helps in maintaining the original state of the vector but also aids the compiler in optimizing machine code for better performance. While seemingly a subtle detail, the use of const provides clarity in function contracts and can assist in avoiding unintended modifications.

In this code example, the multiplyByTwo function remains the same, taking a reference to a vector of integers and multiplying each element by two. The new addition is the findInteger function, which takes a constant reference to a vector of integers ( const vector<int> &arr ) as its parameter.

Inside the function, it searches for a specific integer ( target ) within the vector and prints whether it was found or not.

In the main function, a vector named arr is initialized, and the multiplyByTwo function is called, modifying the vector. The modified vector is then displayed using the copy function and ostream_iterator .

Subsequently, the findInteger function is called twice, once for the original vector and once for the modified vector, showcasing the usage of the const notation to prevent unintentional modifications.

As shown in the output, the original vector remains unaltered during the search operation in the findInteger function, emphasizing the importance of maintaining vector integrity when modifications are undesired.

Let’s discuss another efficient vector manipulation technique in C++: the vector<T>* arr notation. This notation involves passing a pointer to a vector of integers, allowing functions to operate directly on the original vector.

The vector<int>* arr notation signifies the passing of a pointer to a vector of integers. The asterisk ( * ) denotes a pointer, indicating that the function receives the memory address of the original vector.

Using a pointer grants the ability to directly modify the original vector and is particularly useful when handling large datasets or when the function needs to allocate memory for the vector dynamically. However, it also comes with the responsibility of managing memory properly, especially if the vector is dynamically allocated.

In this code example, the multiplyByTwo function takes a pointer to a vector of integers ( vector<int>* arr ). Inside the function, the pointer is dereferenced using the asterisk ( * ) to access the original vector, and each element is then multiplied by two.

This approach allows direct modification of the original vector through the pointer.

In the main function, a vector named arr is initialized with a sequence of integers. The multiplyByTwo function is called, passing the memory address of the vector using the address-of operator ( & ).

The modified vector is then displayed using the copy function and ostream_iterator .

This output demonstrates the effectiveness of using the vector<int>* arr notation. The original vector is modified directly through a pointer, eliminating the need for creating additional copies.

While using pointers adds flexibility, it is crucial to manage memory properly and consider the implications, especially in scenarios involving dynamic memory allocation.

The std::reference_wrapper from the <functional> header provides another convenient workaround for passing vectors by reference. std::reference_wrapper is a lightweight wrapper that behaves like a reference but can be stored in containers that require assignable types.

It is particularly useful when you need to pass references around, such as when working with function parameters. In the context of passing vectors by reference, std::reference_wrapper allows us to create a reference-like object that can be easily passed to functions, overcoming restrictions on directly storing references in certain contexts.

It provides a clean and expressive way to pass references without resorting to pointers.

In this code, the multiplyByTwo function takes a reference to a vector of integers ( vector<int>& arr ) as its parameter. To pass the vector by reference using std::reference_wrapper , we create a reference_wrapper<vector<int>> named arrRef , which wraps the original vector.

The function is then called, allowing us to modify the original vector through the reference wrapper.

In the main function, a vector named arr is initialized with a sequence of integers. A reference_wrapper is created, wrapping the vector, and passed to the multiplyByTwo function.

This enables the function to operate on the original vector directly. The modified vector is then displayed using the copy function and ostream_iterator .

The output shows the original vector is efficiently modified through the reference wrapper, offering a clean and expressive solution for scenarios where reference semantics are desired within functions.

Choosing the appropriate method to pass vectors by reference in C++ depends on the specific requirements of your code. Whether you prioritize efficiency, read-only access, flexibility with pointers, or the clean syntax provided by std::reference_wrapper , understanding these methods will allow you to make informed decisions for optimal vector manipulation in your C++ programs.

Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article - C++ Vector

  • How to Iterate Through a Vector in C++
  • Vector Iterator in C++
  • How to Resize 2D Vector C++
  • How to Calculate Angle Between Two Vectors in C++
  • How to Deallocate a std::vector Object in C++
  • Multidimensional Vectors in C++

<vector>

Std:: vector ::assign, return value, 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)

3.11   Constructing Graphs: shared 🔗 ℹ

syntax ( shared   ( [ id   expr ]   ... )   body   ...+ )

The shared form is similar to letrec , except that special forms of expr are recognized (after partial macro expansion) to construct graph-structured data, where the corresponding letrec would instead produce a use-before-initialization error.

Each expr (after partial expansion) is matched against the following shared-expr grammar, where earlier variants in a production take precedence over later variants:

The prefix: make- id identifier above matches three kinds of references. The first kind is any binding whose name has make- in the middle, and where prefix: id has a transformer binding to structure information with a full set of mutator bindings; see Structure Type Transformer Binding . The second kind is an identifier that itself has a transformer binding to structure information. The third kind is an identifier that has a ' constructor-for syntax property whose value is an identifier with a transformer binding to structure information. A shell-id , meanwhile, must be one of the id s bound by the shared form to a shell-expr .

When the expr s of the shared form are parsed as shared-expr (taking into account the order of the variants for parsing precedence), the sub-expressions that were parsed via early-expr will be evaluated first when the shared form is evaluated. Among such expressions, they are evaluated in the order as they appear within the shared form. However, any reference to an id bound by shared produces a use-before-initialization errror, even if the binding for the id appears before the corresponding early-expr within the shared form.

The shell-id s and shell-expr s (not counting patchable-expr and early-expr sub-expressions) are effectively evaluated next:

A shell-id reference produces the same value as the corresponding id will produce within the body s, assuming that id is never mutated with set! . This special handling of a shell-id reference is one way in which shared supports the creation of cyclic data, including immutable cyclic data.

A shell-expr of the form ( mcons patchable-expr patchable-expr ) , ( vector patchable-expr ... ) , ( box patchable-expr ) , or ( prefix: make- id patchable-expr ... ) produces a mutable value whose content positions are initialized to undefined . Each content position is patched (i.e., updated) after the corresponding patchable-expr expression is later evaluated.

Next, the plain-expr s are evaluated as for letrec , where a reference to an id raises exn:fail:contract:variable if it is evaluated before the right-hand side of the id binding.

Finally, the patchable-expr s are evaluated and their values replace undefined s in the results of shell-expr s. At this point, all id s are bound, so patchable-expr s can create data cycles (but only with cycles that can be created via mutation).

> ( shared   ( [ a   ( cons   1   a ) ] )       a ) #0='(1 . #0#) > ( shared   ( [ a   ( cons   1   b ) ]              [ b   ( cons   2   a ) ] )       a ) #0='(1 2 . #0#) > ( shared   ( [ a   ( cons   1   b ) ]              [ b   7 ] )       a ) '(1 . 7) > ( shared   ( [ a   a ] )   ;   no indirection...       a ) a: undefined;   cannot use before initialization > ( shared   ( [ a   ( cons   1   b ) ]   ;   b is early...              [ b   a ] )       a ) a: undefined;   cannot use before initialization > ( shared   ( [ a   ( mcons   1   b ) ]   ;   b is patchable...              [ b   a ] )       a ) #0=(mcons 1 #0#) > ( shared   ( [ a   ( vector   b   b   b ) ]              [ b   ( box   1 ) ] )       ( set-box!   b   5 )       a ) '#(#&5 #&5 #&5) > ( shared   ( [ a   ( box   b ) ]              [ b   ( vector   ( unbox   a )     ;   unbox after a is patched                         ( unbox   c ) ) ]   ;   unbox before c is patched              [ c   ( box   b ) ] )       b ) #0='#(#0# #<undefined>)
  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators

Related Articles

  • Solve Coding Problems
  • 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...

  • poulami21ghosh
  • utkarshgupta110092

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

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

Inserts, in non-reversing order, copies of elements in rg before pos .

If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise, only the iterators and references before the insertion point remain valid.

Each iterator in the range rg is dereferenced exactly once.

The behavior is undefined if rg overlaps with the container.

[ edit ] Parameters

[ edit ] return value.

An iterator that points at the copy of the first element inserted into vector or at pos if rg is empty.

[ edit ] Notes

[ edit ] example, [ edit ] see also.

  • 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 27 July 2023, at 15:15.
  • This page has been accessed 9,417 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

IMAGES

  1. Understanding Vector insert() in C++

    assign vector by reference c

  2. Vector Example In C++

    assign vector by reference c

  3. An Ultimate Guide to C++ Vector

    assign vector by reference c

  4. Vector Example In C++

    assign vector by reference c

  5. C++ vector Initialization

    assign vector by reference c

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

    assign vector by reference c

VIDEO

  1. Vector

  2. C++ Tutorial 20

  3. C++

  4. 111722 COSC 1337 C++ Vector move assign, reserve and pushback

  5. Vectors in c++ STL

  6. Korkak Vector

COMMENTS

  1. c++

    how to assign vector to object by reference? Ask Question Asked 10 years, 2 months ago Modified 10 years, 2 months ago Viewed 4k times 2 My try: class myClass { std::vector<int> myVector; public: myClass (std::vector<int> &v) { this->myVector = v; } void doSomething () { for (int &num : this->myVector) { num += 100; } } }; in main ():

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

    std::vector<T,Allocator>::assign - cppreference.com cppreference.com Log in Namespaces Page Discussion Variants Views View Edit History Actions std::vector<T,Allocator>:: assign From cppreference.com < cpp ‎ | container ‎ | vector [edit template] C++ Compiler support Freestanding and hosted Language Standard library Standard library headers

  3. ::assign

    <vector> std:: vector ::assign C++98 C++11 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.

  4. Reference initialization

      && && (inside the definition of ) ) : ) &= {,, & &&,}; && Designated list-initialization  , . &&= {., . &&, . can be initialized with an object of type , a function of type , or an object implicitly convertible to . Once initialized, a reference cannot be reseated (changed) to refer to another object.

  5. std::vector

    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 be accessed not only through iterators, but also using offsets to regular pointers to elements.

  6. Standard C++

    For example, with a single type you need both an operation to assign to the object referred to and an operation to assign to the reference/pointer. This can be done using separate operators (as in Simula). For example: Ref<My_type> r :- new My_type; r := 7; // assign to object r :- new My_type; // assign to reference

  7. vector

    reference: allocator_type::reference: for the default allocator: value_type& const_reference: allocator_type::const_reference: ... 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)

  8. ::operator=

    Any elements held in the container before the call are either assigned to or destroyed. Parameters x A vector object of the same type (i.e., with the same template parameters, T and Alloc). il An initializer_list object. The compiler will automatically construct such objects from initializer list declarators. Member type value_type is the type of the elements in the container, defined in ...

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

  10. std::vector::assign

    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> : run this code

  11. c++

    5 Answers Sorted by: 38 You can pass the container by reference in order to modify it in the function. What other answers haven't addressed is that std::vector does not have a push_front member function. You can use the insert () member function on vector for O (n) insertion:

  12. Passing Vector to a Function in C++

    Passing Vector to a Function in C++ Read Courses Practice When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value Pass By Reference When a vector is passed to a function, a copy of the vector is created.

  13. How to Pass Vector by Reference in C++

    Use the vector<T> &arr Notation to Pass a Vector by Reference in C++ One effective way to pass vectors efficiently in C++ is by using the vector<T> &arr notation, allowing functions to operate directly on the original vector without creating unnecessary copies. The vector<T> &arr notation indicates passing a reference to a vector of type T.

  14. std::vector<T,Allocator>::assign_range

    an input_range with reference type convertible to the element type of the container. Type requirements. - std::assignable_from<T&, ranges::range_reference_t<R>> must be modeled. Otherwise, the program is ill-formed. - T must be EmplaceConstructible into the container from *ranges::begin(rg). If R models neither sized_range nor forward_range, T ...

  15. vector::assign

    vector::assign - C++ Reference <vector> (destructions, constructions). All iterators, pointers and references related to this container are invalidated. All copied elements are accessed. All contained elements are modified. if an exception is thrown, the container is in a valid state. allocator_traits::construct <cassert> (assert.h)

  16. 3.11 Constructing Graphs: shared

    The prefix: make-id identifier above matches three kinds of references. The first kind is any binding whose name has make-in the middle, and where prefix: id has a transformer binding to structure information with a full set of mutator bindings; see Structure Type Transformer Binding.The second kind is an identifier that itself has a transformer binding to structure information.

  17. std::vector<bool>::reference

    The std::vector < bool > specialization defines std::vector < bool >::reference as a publicly-accessible nested class. std::vector < bool >::reference proxies the behavior of references to a single bit in std::vector < bool >.. The primary use of std::vector < bool >::reference is to provide an lvalue that can be returned from operator [].. Any reads or writes to a vector that happen via a std ...

  18. c++

    92 a) It cannot, the line you quote doesn't change the reference q, it changes p. b) No the literal is constant, but p is a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot. q = "world"; makes the pointer p point to something else.

  19. 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 value - value to be assigned to the vectorname

  20. std::vector<T,Allocator>::insert_range

    pos. -. iterator before which the content will be inserted ( pos may be the end () iterator) rg. -. a container compatible range, that is, an input_range whose elements are convertible to T. Type requirements. - T must be EmplaceConstructible into vector from *ranges::begin(rg). Also, T must be MoveInsertable into vector and T satisfies ...