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 best solutions below
Related Questions in C++
- C++ using std::vector across boundaries
- Linked list without struct
- Connecting Signal QML to C++ (Qt5)
- how to get the reference of struct soap inherited in C++ Proxy/Service class
- Why we can't assign value to pointer
- Conversion of objects in c++
- shared_ptr: "is not a type" error
- C++ template using pointer and non pointer arguments in a QVector
- C++ SFML 2.2 vectors
- Lifetime of temporary objects
- I want to be able to use 4 different variables in a select statement in c ++
- segmentation fault: 11, extracting data in vector
- How to catch delay-import dll errors (missing dll or symbol) in MinGW(-w64)?
- How can I print all the values in this linked list inside a hash table?
- Configured TTL for A record(s) backing CNAME records
Related Questions in INITIALIZATION
- When should we use / not use initialization in Java?
- Warning when trying to initialize a 2D struct array with two initializer lists
- vector of class pointers initialization
- Does C language specify any implicit initialization for void pointers only?
- Initialization in list - default value
- Declare Two-Dimensional Array - Clarification
- Python: Cleaner ways to initialize
- Can I use the C++11 brace initialization syntax to avoid declaring trivial constructors for simple aggregates?
- C Define size of array inside main for a struct
- Idiomatic way to have different different subclasses in swift have different default values
- Custom class that inherits from UITextField does not work (with custom init) in Swift
- Array initialization error in Verilog
- Object initialization with protocol and class name in swift
- What are the values of a std::vector initialized with a given size?
- c++ initialize other class in constructor
Related Questions in UNASSIGNED-VARIABLE
- C# Script Error "Use of Unassigned variable 'line'?
- Use of unassigned local variable that is assigned
- Why is a local variable assigned in one method, but unassigned in a near-identical method?
- Use of unassigned local variable on finally block
- Stuck in function and booleans
- When does Python create a name record in the local scope
- How to implement operator=() for a class that has a reference member variable?
- C# error CS0165: Use of unassigned local variable - ignoring logic and out reference
- use of unassigned local variable `total`
- Use of unassigned variable error when I am trying to assign values to variables using IF statements
- Error CS0165 Use of unassigned local variable 'json'
- Local variable is unassigned IF I'm going to change it later in the function
- C++ Union fields not set correcly
- c# switch problem
- How can I show a string representation of a nullable DateTime type?
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)
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?
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.