Concepts / Vector Basics and Element Access

Vector Basics and Element Access

Initializing or assigning a vector copies its elements, so the two vectors afterward hold separate copies of every element.

  • Programming

Why a Vector Copy Feels Harmless

Many programmers first meet vectors as a tidy way to hold a list of things. Along the way they build an intuition from simple variables: assigning one number to another is quick and harmless. It is easy to carry that same intuition over to a vector that holds thousands of records, and that carried-over intuition is where trouble starts.

The belief to examine is this: copying a vector is always inexpensive, so you can initialize or assign vectors freely wherever you like. The source material names this as a misconception directly. A vector is not a single small value. It is a container, and copying it means copying the elements it holds. The number of elements matters a great deal.

Before reading on, test the belief yourself. Suppose one vector already exists, and a second vector is created from it. If you change something through the second vector, what do you expect the first vector to contain? Hold that prediction in mind, because the next sections check it against what actually happens.

Following a Copy Step by Step

A vector can be copied in two situations. In an initialization, a new vector is created with the contents of an existing one. In an assignment, an existing vector receives the contents of another. Both situations are carried out by constructors and assignment operators, which are the same mechanisms that govern how copying and moving of vectors work in general.

Both situations follow the same trace. Start with a vector a that holds elements. Run an initialization such as creating b from a. Now ask what exists in memory. The answer is two containers, each with its own block of element storage. The copy did not just record that b is connected to a. It produced a second set of elements.

a element 0Entry 1b element 0Entry 1 copya element 1Entry 2b element 1Entry 2 copy
After b is initialized from a, do a and b share the same elements or does each one own a separate set of elements?

The diagram shows the result the source describes. Each vector holds its own copy of every element, so the two containers are independent from the moment the copy finishes. Assignment works the same way: when an existing vector receives the contents of another, the receiving vector ends up with its own copies of the elements.

What Actually Gets Copied

The key fact is what gets copied. A copy of a vector means copying its elements, not merely recording that one name is connected to the other. Once the copy exists, changes to one container cannot reach the other, because there is no shared storage between them.

b[0]10b[0]99a[0]10a[0]10
Setting b[0] to 99 changes only the b side. The a side keeps its original value.

Here is the prediction the diagram answers. If you modify b[0] after copying a into b, the element a[0] is unaffected. It still holds its original value, because a and b do not share elements. The two containers are independent from that point on, and that independence is exactly what the copy paid for.

Worked example

A phone book copied into a second vector

A phone book is stored in one vector named phone_book, and a second vector named book2 is created from it. A change is then made through book2. What does phone_book look like afterward?

  1. 1
    Initialize the copy

    book2 is created with the contents of phone_book, so book2 receives its own copy of every Entry in the phone book.

  2. 2
    Identify what is separate

    Each vector now holds its own separate copy of every Entry. The containers do not share those entries.

  3. 3
    Change through book2

    The change is made to an Entry held by book2. That change lands only in book2's copy.

  4. 4
    Check phone_book

    phone_book still holds its original Entries, unchanged by the edit made through book2.

Result

phone_book is unaffected. The answer depends on the fact that the initialization copied the elements, not just the connection between the two names.

What do you think happens?

After b is created as a copy of a, and then b[0] is set to 99, what does a[0] print?

  • 10

  • 99

  • It depends on the vector's size

Reveal answer
Answer:

10

The copy duplicated every element, so b[0] and a[0] are stored separately. Changing b[0] leaves a[0] at its original value of 10.

Element Access with Indices

Once a vector holds its elements, you reach an individual element by its index. The expression v[i] selects the element at position i within the vector's storage. The elements are kept in order, so each index maps to one stored element and the indices follow the order in which the elements were stored.

python
Output (expected)
10 99
Notes on the code
  • Line 5 creates a with three elements.
  • Line 6 initializes b from a, which copies the elements.
  • Line 7 changes only b's element at index 0.
  • Line 8 prints a[0] and b[0], showing that the two containers are independent.
v[0]10v[1]20v[2]30next in storagenext in storage
Each index selects the stored element at that position, with indices following the order in which the elements are stored.

Notice that indexing reads or writes the element that is already stored. It does not create a new vector, which is why element access on its own is not the source of the copying cost. The cost comes from initialization and assignment, where the stored elements are duplicated.

The Hidden Cost of Large Copies

The source warns that assignments and initializations that look innocent can become expensive when a vector holds many elements. The reason follows directly from what a copy does: the work grows with the number of elements being copied. A single line of code can therefore hide a large amount of work, and the line itself gives no visual hint of that cost.

Copyduplicates every elementReference or pointerworks on the existingvectorMovehands off the contents
Copying duplicates every element, while a reference or pointer works on the existing vector and a move can hand off the contents when the original is no longer needed.

When copying is undesirable, the source names two alternatives. One is to use references or pointers, which allow code to work with an existing vector without creating a new one. The other is to use move operations, which the source places in the discussion of constructors and assignment operators. Both avoid the element-by-element duplication that a copy performs.

  • Common mistake

    Assuming every vector assignment is cheap because assigning a single number is cheap

    Why it fails

    A vector copy duplicates its elements, so the work grows with how many elements it holds.

    Do this instead

    Before assigning or initializing a large vector, ask whether you truly need a second, independent container.

  • Common mistake

    Copying a vector just to read from it

    What it looks like

    A function receives a vector and only looks at its contents, but its parameter is declared as a plain copy.

    Why it fails

    If the code only needs to look at or work on an existing vector, a copy duplicates elements that were never going to be changed separately.

    Do this instead

    Use a reference or pointer so the code works with the existing vector without creating a duplicate.

  • Common mistake

    Keeping a copy when the original is no longer needed

    Why it fails

    When a value is being handed off, a copy still pays for duplicating every element even though the original is finished with.

    Do this instead

    Use a move operation where the value is handed off and the original is no longer needed.

Choosing std::vector by Default

The source material also gives guidance on which container to reach for. The standard-library vector is described as very flexible and efficient, and it should be used as the default container. Use another container only when there is a solid reason to do so.

Best practice

Start with std::vector for a collection of values. Move away from it only after you have a concrete reason, and measure performance before choosing something else for efficiency. Measuring first keeps you from replacing a container on a guess.

The same discipline applies to copying. Keep the default container, and when a vector is large, decide deliberately between a copy, a reference or pointer, and a move, depending on whether you need two independent containers or only access to one that already exists.

Practicing the Copy Decision

MEDIUM

A function receives a vector of one million records. It only needs to read the first record and never changes the vector. Which parameter style avoids duplicating the elements, and why?

Hints
  • Ask whether the function needs its own independent container or only access to one that already exists.
  • The source says a reference or pointer lets code work with an existing vector without creating a new one.
EASY

After a copy, you modify an element through the new vector. Write one sentence predicting whether the original vector changes, and name the fact about copying that supports your prediction.

Hints
  • Think about what gets duplicated during an initialization.

Key Takeaways

  • Initializing a vector or assigning one to another copies its elements, so the two vectors afterward hold separate copies of every element.
  • Changing an element of one copy does not change the other, because the copy duplicated the elements rather than linking the two names.
  • Copy cost grows with the number of elements, so innocent-looking assignments can be expensive for large vectors.
  • Where copying is undesirable, use references or pointers, or move operations, to avoid duplicating the elements.
  • Use the standard-library vector as the default container, and measure performance before choosing something else for efficiency.

Related concepts

More concepts starting with V