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


is there simple way find indices of non empty entries of pre-allocated vector?
1 way loop through vector. slow if memory allocated vector large , number of non empty entries less.
below example code. in have entries indices 5,9,9,15, task identify indices 5,9,15 vector x of size 20. please suggest simple way or better data structure 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, assume 0 entry mean empty entry (a map without elements).

i don't think possible remove iteration cost, moved other points of program (initialization, element insertion, ...) point want identify index.

for example, can encapsulate 2 containers in class: vector propose, , set<size_t> indexes of empty entries in vector. both should not directly accessible outside class (private). must initialize set indexes in range vector (iteration here). insertion of new elements should through class interface remove index set. removal of new elements (including removing elements map of entry, detect when going empty). identify empty entry indexes, well, have of them in set.

as can see, approach move iteration-cost point want identify empty entry indexes initialization, adding complexity (and cost) anywhere else.

depending of needs, containers use different or approach might not useful @ all.

update: approach above right if problem looking empty entry indexes. solve problem in question (identify non-empty entry indexes), approach be:

  • using set<size_t> store non-empty indexes,
  • nothing set @ initialization.
  • when inserting new element, insert index in set
  • when removing element of map in vector, check if map become empty remove index in case
  • the set contains indexes of non-empty entries.

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -