Can someone please help me understand what the following code means and how it translates to C#?
unsigned int b = 100;
std::vector<bool> a (b, false);
if it was something like this:
vector<bool> a;
I'd probably just go:
List<bool> a;
Is that correct?
But I don't don't know c++, so I don't understand how a uint and a bool are being passed to a vector of type bool? Maybe it should be something like this?
MyGenericList<int, bool> a = new MyGenericList<int, bool>(b, false);
std::vector<bool>
is special, it is implemented as a bit array in C++. In other words, 1 byte stores 8 elements of the vector, the most condense possible way to create an array of bool. That's available in .NET as well, the exact equivalent declaration is:
int b = 100;
System.Collections.BitArray a = new System.Collections.BitArray(b);
If this array only ever contains 100 elements then, meh, don't bother. If it is going to contain a million then, yes, do bother.
As the other answers say, the C++ code creates something like an array or list with 100 elements, all false
. The equivalent in C# would be:
var a = new bool[100];
Or if you don't need a fixed size:
var a = new List<bool>(100);
// or, if the initial capacity isn't important
var a = new List<bool>();
Since the default bool
value is false
, you don't need to explicitly specify it anywhere. If you wanted true
(or, eg in a list of int
s, to default to -1
), you'd have to loop through it after you created it:
var a = new bool[100];
for (var i = 0; i < a.Length; i++)
a[i] = true;
std::vector<bool> a (b, false);
creates a vector (an array or kind of a C# list) that is 100 bools long and initializes these bool
s to false.
A note: Do not use std::vector<bool>
.
The first argument is the size of vector while second is it's element (see handly C++ reference ). So
std::vector<bool> a(100, false);
Create vector of 100 elements, elements of which are false
.
As pointed out by Scarlet std::vector<bool>
is 'strange' (it does not have full C++ container interface. I'd not go so far to say 'don't use it' but it's important to know that it might behave strange - the ling above is to 'normal' vector).
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.