algorithm
programming
vector-manipulation
indices
data-structure

Reorder vector using a vector of indices

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Reordering a vector with another vector of indices is a common operation in C++ and data-processing code. The crucial first step is to define what the index vector means. In the most common convention, indices[i] tells you which element from the original vector should move into position i in the result.

The Easiest Correct Solution: Build a New Vector

If indices[i] means "take element v[indices[i]]," then the direct solution is to allocate a new vector and fill it in that order.

cpp
1#include <iostream>
2#include <vector>
3
4int main() {
5    std::vector<char> v = {'a', 'b', 'c', 'd'};
6    std::vector<std::size_t> indices = {2, 0, 3, 1};
7
8    std::vector<char> reordered(indices.size());
9    for (std::size_t i = 0; i < indices.size(); ++i) {
10        reordered[i] = v[indices[i]];
11    }
12
13    for (char c : reordered) {
14        std::cout << c << ' ';
15    }
16}

Output:

text
c a d b

This approach is simple, safe, and usually fast enough. It also works even if indices repeat.

Validate the Indices

Before reordering, make sure the index vector is valid for the source vector:

  • every index is within bounds
  • the meaning of duplicates is intentional
  • the destination size is what you expect

A checked version might look like this:

cpp
1#include <stdexcept>
2#include <vector>
3
4template <typename T>
5std::vector<T> reorder(const std::vector<T>& v, const std::vector<std::size_t>& indices) {
6    std::vector<T> out;
7    out.reserve(indices.size());
8
9    for (std::size_t idx : indices) {
10        if (idx >= v.size()) {
11            throw std::out_of_range("index out of range");
12        }
13        out.push_back(v[idx]);
14    }
15
16    return out;
17}

That extra validation is worth it when the permutation comes from user input, data files, or another computation.

In-Place Reordering Is Harder

If you want to reorder the vector in place, the problem becomes more subtle. In-place reordering only makes sense when indices represents a true permutation:

  • same length as the vector
  • every source position appears exactly once

If indices repeat, an in-place algorithm would overwrite values that are still needed later. That is why the out-of-place solution above is the general answer.

For a true permutation, one in-place approach uses cycle decomposition. That is more memory-efficient, but also more complex and easier to get wrong. Unless memory pressure is severe, building a new vector is usually the better engineering choice.

Understand Duplicate Indices

The title mentions a duplicate. If the index list contains duplicates, that changes the semantics:

cpp
v = {'a', 'b', 'c'};
indices = {1, 1, 2};

The result becomes:

text
b b c

That is valid for an out-of-place reorder because positions can reuse the same source element. It is not a permutation anymore. That is another reason the copy-based solution is the safe default.

Use Standard Algorithms Carefully

C++ standard algorithms can help with related tasks such as sorting indices or stable partitioning, but there is no one built-in standard algorithm that says "reorder vector by this arbitrary index mapping" more clearly than a small loop does.

In this case, the explicit loop is usually the most readable implementation. It tells the reader exactly how the mapping works.

Performance Considerations

The copy-based reorder is O(n) and uses O(n) extra space. For most workloads, that is completely fine. The real performance questions are usually:

  • how large the vector is
  • whether bounds checks are needed
  • whether repeated indices are common

Trying to force an in-place solution for moderate-sized vectors is often premature optimization.

Common Pitfalls

  • Not defining what the index vector means before writing code.
  • Using an in-place algorithm when indices are not a true permutation.
  • Forgetting bounds checks when indices come from external input.
  • Assuming duplicate indices are invalid when the intended output actually allows repeated elements.
  • Overcomplicating a simple reorder that could be handled by a direct O(n) copy.

Summary

  • The clearest solution is usually out[i] = v[indices[i]].
  • Building a new vector is simple, correct, and works even when indices repeat.
  • In-place reordering is only appropriate for true permutations.
  • Always validate index bounds when the mapping is not guaranteed.
  • Be explicit about the meaning of the index vector before choosing an algorithm.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.