Let us say I'm initializing a vector vector<bool> V(n);. Is there a way I can know if V[n] is initialized or not? I need this for dynamic programming purposes. If the V[n] is initialized, I would utilize the value V[n] to obtain the result. If it's not initialized yet, I'd apply a function foo(.., n) or something to obtain the value of V[n]. I am asking this because I don't want to initialize a vector<int> V(n, -1); with 3 states like -1(for unassigned, or yet to find), 0(for false), and 1(for true). Instead, if there is a way to know if a variable V[n] is unassigned, I may be able to save some space for large values of n.
Is there a way to check a variable is already initialized in c++?
227 views Asked by madhan01 At
1
There are 1 answers
Related Questions in C++
- How to immediately apply DISPLAYCONFIG_SCALING display scaling mode with SetDisplayConfig and DISPLAYCONFIG_PATH_TARGET_INFO
- Why can't I use templates members in its specialization?
- How to fix "Access violation executing location" when using GLFW and GLAD
- Dynamic array of structures in C++/ cannot fill a dynamic array of doubles in structure from dynamic array of structures
- How do I apply the interface concept with the base-class in design?
- File refuses to compile std::erase() even if using -std=g++23
- How can I do a successful map when the number of elements to be mapped is not consistent in Thrust C++
- Can std::bit_cast be applied to an empty object?
- Unexpected inter-thread happens-before relationships from relaxed memory ordering
- How i can move element of dynamic vector in argument of function push_back for dynamic vector
- Brick Breaker Ball Bounce
- Thread-safe lock-free min where both operands can change c++
- Watchdog Timer Reset on ESP32 using Webservers
- How to solve compiler error: no matching function for call to 'dmhFS::dmhFS()' in my case?
- Conda CMAKE CXX Compiler error while compiling Pytorch
Related Questions in INITIALIZATION
- How do I initialise a class within a class
- Initializing problem with a variable for a distance calculator in Java with if and else statement
- Is there are a way to determine process stages from inside a library
- Could an unitialized pointer be a NULL pointer?
- Initialization of an empty Bash indexed array
- Flutter dropdownMenue with conditions
- How to migrate to standalone in angular
- for loop initialization failure
- Why does my console.log output the incorrect HTML slider value in JavaScript?
- Why does VS Code give me this error? : non-aggregate type 'list<int>' cannot be initialized with an initializer listgcc
- Initialize std::array of certain type, but any size?
- Why would anyone declare a variable before defining it? Please provide example
- Why is clang-tidy giving me an uninitialized error for this c++ code?
- Why is my C++ program running fine with the debugger but not without it?
- Is there a way trough some method or property to postopone initialization of setGrid method of some ChildComponent in Angular?
Related Questions in UNASSIGNED-VARIABLE
- Is there a way to check a variable is already initialized in c++?
- Python says "UnboundLocalError: local variable 'key' referenced before assignment"
- Error CS0165 Use of unassigned local variable 'json'
- Use of unassigned variable error when I am trying to assign values to variables using IF statements
- Local variable is unassigned IF I'm going to change it later in the function
- How to assigne a dataframe mean to specific rows of dataframe?
- How to resolve this compilation error "Using unassigned local variable 'hak'" when using goto?
- How to get around use of unassigned variable that can never happen?
- Unity 3D warning CS0414: The field <field> is assigned but its value is never used
- Variable 'Button' never assigned (Java using android studio)
- Use of unassigned local variable? Can someone explain?
- Jupyter Notebook, NameError: is not defined, %%time prevents assignment
- C# Beginner - "Use of Unassigned Local Variable" Issue
- Memory problems shown at run time because of the initialisation of an int data type
- UnboundLocalError: local variable '(Var)' referenced before assignment
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Popular Tags
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Just gathering all the comments into a readable answer.
All the members of a vector that exist are intialised, so to solve the problem we really need to represent 3 states, Uninitialised, False, True, and create the entries as Uninitialised. We would want the vector to initially contain nodes in state Uninitialised.
So how best to represent this tristate? Considerations: Code maintainability; speed of access; memory usage.
vector<bool>is a special implementation ofvectorwhich /may/ be optimised to store more than 1 value per byte. It is possible to squeeze 8 bool bits into a byte. So a vector of 1000 bool will only use 125 bytes.If you create any other vector of data, it will store an object of the size of that data type, so char, for example, or more exactly a vector<int8_t>, would use 1 byte per entry. 1000 chars would use 1000 bytes.
A
vector<int>would use a number of bytes per entry, probably at least 4, so would cost 4000 bytes to hold 1000 elements.But you would only be using 3 of the possible 255 states in a char, so using a vector of char would be more efficient than a vector of int, but is still somewhat wasteful of storage vs the
vector<bool>. You might not care about that, and that is a fair approach. The code generated byvector<bool>is more complex than for the normal vector, so your code would be slower..Let's go mad and use an enum:
But what about
vector<bool>?The tighter forms suggested are to use 2 vectors of bool, one to say whether the entry is valid and the second to say that its value is set. This will cost 2*125 bytes, or 256 bytes for 1000 entries. That is still a saving over a vector of char.
Or you could write your own wrapper for vector where you treat 2 consecutive entries as the valid and set flags, and you allocate it twice as large as you wanted. This has the advantage of locality of reference, and potentially the optimiser can somewhat merge consecutive questions "is it valid" then "is it set".
So you save some storage, for the cost of some additional complexity (speed loss). You could wrap this in a class with accessors to hide the complexity.
If you were going to do that, you could write your own wrapper round a
vector<unit8_t>which divides the input index by 4 and splits the stored value into 4 2-bit tri-state values. This would possibly be slightly faster overall, as you would not separately ask the vector "is it valid" then "is it set".You /could/ squeeze more than 4 tristates into a byte - you can get 5, but that generates very slow code all round. The compiler knows how to divide by 4 very efficiently, and is less able to quickly divide by 5, or by powers of 3.
These days we tend to choose speed and simplicity over space saving, so do the
vector<bool>thing for fun if you like, but stick with the vector of char.That's all good.
I guess the other question I have to ask, though, is under what conditions is an entry invalid? Are they made valid sequentially? If the number of valid entries an indication that the higher indices are not yet valid?
In which case you could just start with an empty
vector<bool>and push new values onto it as you need them - useindex < size()to decide if the current index is valid or not? You can usereserve()to avoid the vector reallocating as it grows. This saves half the required storage, and keeps the code complexity manageable, so it is worth considering.Of course in your case initialised/validity may be a completely random state in which case this is not an option for you.