简体   繁体   中英

finding non empty indices of a pre-allocated vector C++

Is there any simple way to find the indices of non empty entries of a pre-allocated vector?
one way is to simply loop through the vector. But it is very slow if memory allocated to vector is large and the number of non empty entries is very less.
Below is the example code. In that I have entries for indices 5,9,9,15 , now the task is to identify the indices 5,9,15 from the vector x of size 20 . Please suggest some simple way or even a better data structure to do this will be helpful.

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector <map<int,int>> x(20);
    x[5].insert({ 4,10002 });
    x[9].insert({2,20});
    x[9].insert({ 3, 60 });
    x[15].insert({ 11, 60 });

    return 0;
}

First, I assume for zero entry you mean empty entry (a map without elements).

I don't think is possible to remove the iteration cost, but it could be moved to other points of the program (initialization, element insertion, ...) from the point where you want to identify those index.

For example, you can encapsulate two containers in a class: the vector you propose, and a set<size_t> with the indexes of the empty entries in the vector. Both should be not directly accessible outside the class ( private ). You must to initialize the set with all indexes in the range vector (iteration here). The insertion of new elements should be through the class interface to remove that index from the set. The removal of new elements too (including removing elements from the map of any entry, to detect when it is going to be empty). To identify the empty entry indexes, well, you have all of them in the set.

As you can see, this approach move the iteration-cost from the point where you want to identify the empty entry indexes to the initialization, adding complexity (and cost) to anywhere else.

Depending of your needs, the containers to use could be different or this approach might be not useful at all.

UPDATE: The approach above is right if the problem is looking for empty entry indexes. To solve the problem in the question (identify the non-empty entry indexes), the approach would be:

  • using set<size_t> to store non-empty indexes,
  • nothing to do with the set at initialization.
  • when inserting a new element, insert that index in the set
  • when removing an element from any of the map in the vector, check if the map become empty to remove the index in that case
  • the set will contains the indexes of non-empty entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM