Mastering std::vector Operations in C++

Instantiation and Initial Setup

Creating an empty dynamic array:

std::vector<int> emptyVec;

Initializing with a predefined set of values:

std::vector<int> initialVec = {10, 20, 30, 40};

Setting a predefined size with a uniform default value:

std::vector<int> sizedVec(5, -1); // Generates a vector with 5 elements, all set to -1

Adding Elements

Appending to the end:

initialVec.push_back(50);

Inserting at a specific position:

initialVec.insert(initialVec.begin() + 2, 25); // Inserts 25 before the 3rd element

Direct Construction vs Copy/Move: The distinction between push_back and emplace_back lies in how the object is instantiated. push_back requires an existing object or generates a temporary one, subsequently copying or moving it into the allocated storage. Conversely, emplace_back forwards its arguments directly to the in-place constructor, bypassing the creation of intermediate temporaries, which often results in better performance.

std::vector<std::pair<int, std::string>> dataVec;
dataVec.push_back(std::make_pair(1, "alpha")); // Creates a temporary pair, then moves or copies it
dataVec.emplace_back(2, "beta"); // Constructs the pair directly inside the vector memory

Element Retrieval

Index-based access:

int firstItem = initialVec[0];

Traversing via iterators:

for (auto iter = initialVec.begin(); iter != initialVec.end(); ++iter) {
    std::cout << *iter << " ";
}

Modern range-based traversal:

for (const auto& val : initialVec) {
    std::cout << val << " ";
}

Removing Items

Dropping the last item:

initialVec.pop_back();

Erasing specific positions or ranges:

initialVec.erase(initialVec.begin() + 1); // Removes the 2nd item

Memory and Dimension Management

Current item count:

size_t count = initialVec.size();

Checking for emptiness:

bool isBlank = initialVec.empty();

Maximum allocatable size:

size_t upperLimit = initialVec.max_size();

Adjusting dimensions:

initialVec.resize(8); // Expands or shrinks; newly added elements are default-initialized

Pre-allocating memory:

initialVec.reserve(100); // Allocates raw capacity without altering the element count

Utility Functions

Wiping all data:

initialVec.clear();

Copying and transferring ownership:

std::vector<int> cloneVec(initialVec); // Deep copy construction
std::vector<int> targetVec;
targetVec = initialVec; // Deep copy assignment

// Transfer semantics
std::vector<int> movedVec(std::move(initialVec)); // Moves resources, initialVec is left empty

Ordering elements:

std::sort(initialVec.begin(), initialVec.end());

Locating a specific value:

auto searchIter = std::find(initialVec.begin(), initialVec.end(), 20);
if (searchIter != initialVec.end()) {
    // Value located successfully
}

Tags: C++ std::vector Data Structures STL

Posted on Sun, 27 Sep 2026 16:46:14 +0000 by SoreE yes