Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to build sparse array in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>

/*
The sparse array stores only non‑zero values.
We scan it to find the maximum index.
We allocate a dense vector of size maxIndex + 1, filled with zeros.
We copy each sparse entry into its position.
*/

// Sparse array type
using SparseArray = std::unordered_map<size_t, int>;

// Convert sparse → dense
std::vector<int> buildDense(const SparseArray& sa) {
    // Find the largest index so we know how big the dense array must be
    size_t maxIndex = 0;
    for (const auto& [index, value] : sa) {
        maxIndex = std::max(maxIndex, index);
    }

    // Allocate dense array filled with zeros
    std::vector<int> dense(maxIndex + 1, 0);

    // Copy sparse values into dense array
    for (const auto& [index, value] : sa) {
        dense[index] = value;
    }

    return dense;
}

int main() {
    // Sparse entries (zero values omitted)
    SparseArray sa = {
        {2, 10},
        {10, 7},
        {8, 42},
        {3, 5}
    };

    auto dense = buildDense(sa);

    std::cout << "Dense array:\n[ ";
    for (int v : dense) {
        std::cout << v << " ";
    }
    std::cout << "]\n";
}


/*
run:

Dense array:
[ 0 0 10 5 0 0 0 0 42 0 7 ]

*/

 



answered 15 hours ago by avibootz
edited 15 hours ago by avibootz
...