Given an array map with size of 256, what is the best way to initialize it so that each element is false?
bool map[256];
for (int i=0; i<256; i++)
{
map[i] = false;
}
Thank you
bool map[256] = { false };
edit: for a reference to the standard as to why this is legal, see the answers below.
bool map[256] = {false};
(C++ also allows bool map[256] = {};. The above works in C too.)
This will set map[0] to false, and "default-initialize" the rest of 255 members (C++98 §8.5.1/7: "If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized"; C99 §6.7.8/21).
For bool, "default-initialize" means set to (bool)0, i.e. false (C++98 §8.5/5; C99 §6.7.8/10).
Note that this method doesn't work if you want to initialize to true.
Like this:
bool map[256] = { 0 };
Some would say this:
bool map[256] = {};
But to me that just looks a little weird.
Why use "0" rather than "false"? It's not a big deal, but I do it because the array initializer is in effect padded out to the size of the array with 0, not with copies of the first element. Since the initialization of elements 1 through 255 is defined in terms of the value "0" (which of course converts to false), I see no harm in element 0 being initialized with "0" too. Having a "0" at the end of a too-short initializer list for scalar types reminds me of what's really going on.
Specifically, the standard defines this at 8.5.1/7 (initializer list shorter than array), and 8.5/5 (value-initializing a bool is equivalent to initializing it with the value 0 converted to bool).
Absent a reason to do otherwise, the best choice is probably to use a vector:
std::vector<bool> map(256, false);
vector<bool>, however, is a specialization that's rather different from what you might expect. Depending on the situation, you might prefer:
std::vector<char> map(256, false);
In C++, X = { 0 } is an idiomatic universal zero-initializer. This was a feature carried forward from C.
bool map[256] = { 0 };
Related
What is the best way to have three value Boolean variable in c++?
I would like to have fields set to true, false or not set at all in my array.
If I declare them this way:
t[0] = true;
t[1] = false;
t[2] = NULL;
When I test the condition I get:
t[2] is false
You might want to look at boost.tribool: http://www.boost.org/doc/libs/1_60_0/doc/html/tribool.html
This should work:
t[0] = true;
t[1] = false;
t[2] = -1;
Or if you only need 3 states but perhaps would like more at some point, an enum is great:
enum STATES
{
NULL_STATE = -1, // you can manually specify -1 to give it a special case value
FALSE, // will be equal to 0
TRUE // will be equal to 1
};
No matter what though, 0/false is the only thing that returns false in an if() statement. -1 and true both return true.
You may want to use a switch like this to deal with 3+ states:
switch (var) // may need to cast: (int)var
{
case 1:
case 0:
case -1:
};
Alternatively if you want to stick to an if statement block, you could do something like this:
if (var == -1) // or (var == NULL_STATE)
{}
else if (var) // true condition
{}
else // false
{}
Consider using std::experimental::optional<bool> (if your C++ standard library has it), or boost::optional<bool> (www.boost.org).
I believe std::optional is a candidate for C++17 so if you adopt one of the above then your refactoring effort to C++17 ought to be minimal.
If you don't like using things that are not (yet?) in the "proper" C++ standard library, then consider
Something based around std::unique_ptr<bool>
A std::pair<bool, bool>
A good old-fashioned enum with 3 values.
You could use boost::optional
http://www.boost.org/doc/libs/1_60_0/libs/optional/doc/html/index.html
boost::optional<bool> myBooleanVariable;
I agree that tribool can be better if you don't need the uninitialised values to be NULL. Where comparing optional and tribool, the documentation says:
First, it is functionally similar to a tristate boolean (false, maybe, true) —such as boost::tribool— except that in a tristate boolean, the maybe state represents a valid value, unlike the corresponding state of an uninitialized optional. It should be carefully considered if an optional instead of a tribool is really needed.
Source: http://www.boost.org/doc/libs/1_60_0/libs/optional/doc/html/boost_optional/a_note_about_optional_bool_.html
What is the best way to have three value Boolean variable in c++?
Boolean values by definition only have 2 possible states - True or False.
If you want to have another state for 'invalid' or 'not set' then you need to encapsulate the bool variable in some other data-types.
The right solution depends on what you want to do with that variable.
For simple comparisons (if-else and switch) scoped enums (c++11) should be preferred.
enum class tristate{true,false,undefined=0};
They are simple, easy to use and understand and offer type safety over plane old enums. As they are type-safe you can not accidentally compare it with different types of enums or numeral types, But it also means you can not use bitfiddling and integer-tricks either.
Unless a different type is specified an enum class is a numerical type which gets initialized to '0'. that means by assigning the value '0' to one of the enum-values you can make that the default state.
tristatet[7];
t[1] = tristate::true;
t[2] = tristate::false;
t[3] = tristate::undefined;
t[4] = false; //error
t[5] = 0; //error
t[6] = null; //error
t[0] == true; //error
t[0] == tristate::true; // false
t[0] == tristate::undefined; // true
Of course you can use that in a switch-statement:
switch(t[2]) {
case tristate::true:
foo(); break;
case tristate::false:
bar(); break; //t[2] was set to tristate::false
case tristate::undefined :
doNothing(); break;
}
You can use std::optional for this:
std::optional<bool> t[3];
t[0] = true;
t[1] = false;
t[2] = std::nullopt;
for (auto const& i : t)
if (i.has_value()) std::cout << i.value() << '\n';
output:
1
0
I also believe an enum declaration is the cleaner and simplest solution.
A small note on the size of the new type: enums are usually (depending of course on the compiler) backed by integers, so you are allocating something like 32 or 64 bits to actually use 2 bits.
In newer C++ (C++11), you can specify the underlying type of the enum (to an existing integral type). For example:
enum tribool: uint8_t {False = 0, True = 1, Unknown = 2};
...
enum tribool f = tribool::False;
I am trying specify a condition by saying that if an array is not equal to an array run loop. So for example:
array1 [1,2,3]
array2 [1,2,3]
Here array1 does equal array2 as the elements in 0 in both arrays are the same, the elements in 1 in both arrays are the same and so on...
The code I have so far doesn't seem to work. Is there a way of comparing two arrays and if all elements in one match all the elements in the second one the condition is true.
Here is my test code:
int C1Mean[3];
int C2Mean[3];
int prv_mean1[3];
int prv_mean2[3];
while (C1Mean[3] = prv_mean1[3] && C2Mean[3] = prv_mean2[3])
{
//code
}
Thanks chaps.
As commented you access your arrays out of bounds, and you are using assignments (single =) instead or comparisons (==).
To compare your arrays (element by element), you can use std::equal :
while(std::equal(std::begin(C1Mean), std::end(C1Mean), std::begin(prv_mean1))
&& std::equal(std::begin(C2Mean), std::end(C2Mean), std::begin(prv_mean2)))
{
...
}
Or without c++11 :
while(std::equal(C1Mean, C1Mean + sizeof C1Mean / sizeof *C1Mean, prv_mean1)
&& std::equal(C2Mean, C2Mean + sizeof C2Mean / sizeof *C2Mean, prv_mean2))
{
...
}
In c++11, you may use std::array, and use ==:
std::array<int, 3> C1Mean;
std::array<int, 3> C2Mean;
std::array<int, 3> prv_mean1;
std::array<int, 3> prv_mean2;
while (C1Mean == prv_mean1 && C2Mean == prv_mean2)
{
//code
}
You are not using comparison operator (==) but assignment (=), so you change the value of CMean[i] in the condition and the condition would be false only when one of prv_mean2 would be equal to zero. And no, you can't compare the whole arrays.
If you are able to use c++11 you can use a generic function. The generic function is:
bool equal(beginIterator, endIterator, beginIterator Other);
This generic function will compare all values in a range. Note that the second array must be at least as long as the first array.
Since an array is nog an object you cannot use arr.begin () and you should use std::begin(arr) and std::end(arr). These functions come with #include.
Furthermore, if you can use c++11 you can also use the standad container std::array or std::vector. Then you can just state arr1 == arr2.
Note: I wrote this on my mobile and didn't check whether the generic function actually works on arrays. I will check this when at home again and eventually remove my post.
You can create a function to compare the two arrays that will return 1 if they are equal and 0 otherwise. Say, for example,
while(areEqual(C1Mean,prv_mean1) && areEqual(C2Mean,prv_mean2))
{
//Perform your task
}
where
int areEqual(int array1[],int array2[])
{
//compare them and return 1 if equal else return 0;
}
It seems like you need a double equals("=="). Try:
while (C1Mean[3] == prv_mean1[3] && C2Mean[3] == prv_mean2[3])
{
//code
}
I need method, that return numbers of non empty elements of array of ints. sizeof(arr)/sizeof(type), like below:
int table[255]={1,2,3,'a','b'};
cout << "size of: " << sizeof(table)/sizeof(int) << endl;
returns 255, but I need to count elements so the result will be 5.
Shall I make my own while loop or is there any embedded function (I use Visual Studio 2010)?
Assuming that a non-empty element for T array[N] = {}; is the one that is default-initialized - T t{};, the answer is: yes, there is a standard algorithm for counting elements that match a given pattern, or satisfy a given condition, which is std::count
// include header file where the algorithm is defined:
#include <algorithm>
// use std::count to count 0 elements, which is a default value all elements
// are initialized with for int tab[N] = {};
// and subtract this value from the total number of elements of array
int howMany = 255 - std::count(table, table + 255, 0);
// table and table+255 specify the ranges the algorithm operate on
If you are using C++, why not using C++ containers like std::vector and use <algorithm> ?
Anyway, sizeof() will ALWAYS return 255 * sizeof(int) here because the table will contains 255 ints in memory.
8.5.1.7
If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member
not explicitly initialized shall be initialized from an empty initializer list. For int, expression of the form int(),that is, 0.
You could use std::count from algorithm but there is one issue
int table[255]={1,0 <<< this value were stetted by user and it is not an 'empty',3,'a','b'};
So how to distinct 0 assigned by default initializer and 0 that comes as actual value? As a solution you probably should use some INVALID_VALUE definition to set values for elements in your array because 0 is not a greatest choice to mark value as unassigned. And init your array as
memset(table, INVALID_VALUE, table_size);
It can be done by writing own function's template, like this:
template<typename It>
unsigned count_non_val(It first, It last, const decltype(*first)& val){
unsigned result=0;
for(It i=first; i!=last; ++i)
if(*i!=val)
++result;
return result;
}
//Usage:
std::cout<<count_non_val(table, table+255, 0)<<'\n';
This question already has answers here:
Initialization of all elements of an array to one default value in C++?
(12 answers)
Closed 4 months ago.
I'm trying to initialize an int array with everything set at -1.
I tried the following, but it doesn't work. It only sets the first value at -1.
int directory[100] = {-1};
Why doesn't it work right?
I'm surprised at all the answers suggesting vector. They aren't even the same thing!
Use std::fill, from <algorithm>:
int directory[100];
std::fill(directory, directory + 100, -1);
Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:
template <typename T, size_t N>
T* end(T (&pX)[N])
{
return pX + N;
}
Giving:
int directory[100];
std::fill(directory, end(directory), -1);
So you don't need to list the size twice.
I would suggest using std::array. For three reasons:
1. array provides runtime safety against index-out-of-bound in subscripting (i.e. operator[]) operations,
2. array automatically carries the size without requiring to pass it separately
3. And most importantly, array provides the fill() method that is required for
this problem
#include <array>
#include <assert.h>
typedef std::array< int, 100 > DirectoryArray;
void test_fill( DirectoryArray const & x, int expected_value ) {
for( size_t i = 0; i < x.size(); ++i ) {
assert( x[ i ] == expected_value );
}
}
int main() {
DirectoryArray directory;
directory.fill( -1 );
test_fill( directory, -1 );
return 0;
}
Using array requires use of "-std=c++0x" for compiling (applies to the above code).
If that is not available or if that is not an option, then the other options like std::fill() (as suggested by GMan) or hand coding the a fill() method may be opted.
If you had a smaller number of elements you could specify them one after the other. Array initialization works by specifying each element, not by specifying a single value that applies for each element.
int x[3] = {-1, -1, -1 };
You could also use a vector and use the constructor to initialize all of the values. You can later access the raw array buffer by specifying &v.front()
std::vector directory(100, -1);
There is a C way to do it also using memset or various other similar functions. memset works for each char in your specified buffer though so it will work fine for values like 0 but may not work depending on how negative numbers are stored for -1.
You can also use STL to initialize your array by using fill_n. For a general purpose action to each element you could use for_each.
fill_n(directory, 100, -1);
Or if you really want you can go the lame way, you can do a for loop with 100 iterations and doing directory[i] = -1;
If you really need arrays, you can use boosts array class. It's assign member does the job:
boost::array<int,N> array; // boost arrays are of fixed size!
array.assign(-1);
It does work right. Your expectation of the initialiser is incorrect. If you really wish to take this approach, you'll need 100 comma-separated -1s in the initialiser. But then what happens when you increase the size of the array?
use vector of int instead a array.
vector<int> directory(100,-1); // 100 ints with value 1
It is working right. That's how list initializers work.
I believe 6.7.8.10 of the C99 standard covers this:
If an object that has automatic
storage duration is not initialized
explicitly, its value is
indeterminate. If an object that has
static storage duration is not
initialized explicitly, then:
if it has pointer type, it is initialized to a null pointer;
if it has arithmetic type, it is initialized to (positive or unsigned)
zero;
if it is an aggregate, every member is initialized (recursively) according
to these rules;
if it is a union, the first named member is initialized (recursively)
according to these rules.
If you need to make all the elements in an array the same non-zero value, you'll have to use a loop or memset.
Also note that, unless you really know what you're doing, vectors are preferred over arrays in C++:
Here's what you need to realize about containers vs. arrays:
Container classes make programmers more productive. So if you insist on using arrays while those around are willing to use container classes, you'll probably be less productive than they are (even if you're smarter and more experienced than they are!).
Container classes let programmers write more robust code. So if you insist on using arrays while those around are willing to use container classes, your code will probably have more bugs than their code (even if you're smarter and more experienced).
And if you're so smart and so experienced that you can use arrays as fast and as safe as they can use container classes, someone else will probably end up maintaining your code and they'll probably introduce bugs. Or worse, you'll be the only one who can maintain your code so management will yank you from development and move you into a full-time maintenance role — just what you always wanted!
There's a lot more to the linked question; give it a read.
u simply use for loop as done below:-
for (int i=0; i<100; i++)
{
a[i]= -1;
}
as a result as u want u can get
A[100]={-1,-1,-1..........(100 times)}
I had the same question and I found how to do, the documentation give the following example :
std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 (not in C++14)
So I just tried :
std::array<int, 3> a1{ {1} }; // double-braces required in C++11 (not in C++14)
And it works all elements have 1 as value. It does not work with the = operator. It is maybe a C++11 issue.
Can't do what you're trying to do with a raw array (unless you explicitly list out all 100 -1s in the initializer list), you can do it with a vector:
vector<int> directory(100, -1);
Additionally, you can create the array and set the values to -1 using one of the other methods mentioned.
Just use this loop.
for(int i =0 ; i < 100 ; i++) directory[i] =0;
the almighty memset() will do the job for array and std containers in C/C++/C++11/C++14
The reason that int directory[100] = {-1} doesn't work is because of what happens with array initialization.
All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.
ints which are implicitly initialized are:
initialized to unsigned zero
All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.
C++11 introduced begin and end which are specialized for arrays!
This means that given an array (not just a pointer), like your directory you can use fill as has been suggested in several answers:
fill(begin(directory), end(directory), -1)
Let's say that you write code like this, but then decide to reuse the functionality after having forgotten how you implemented it, but you decided to change the size of directory to 60. If you'd written code using begin and end then you're done.
If on the other hand you'd done this: fill(directory, directory + 100, -1) then you'd better remember to change that 100 to a 60 as well or you'll get undefined behavior.
If you are allowed to use std::array, you can do the following:
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
template <class Elem, Elem pattern, size_t S, size_t L>
struct S_internal {
template <Elem... values>
static array<Elem, S> init_array() {
return S_internal<Elem, pattern, S, L - 1>::init_array<values..., pattern>();
}
};
template <class Elem, Elem pattern, size_t S>
struct S_internal<Elem, pattern, S, 0> {
template <Elem... values>
static array<Elem, S> init_array() {
static_assert(S == sizeof...(values), "");
return array<Elem, S> {{values...}};
}
};
template <class Elem, Elem pattern, size_t S>
struct init_array
{
static array<Elem, S> get() {
return S_internal<Elem, pattern, S, S>::init_array<>();
}
};
void main()
{
array<int, 5> ss = init_array<int, 77, 5>::get();
copy(cbegin(ss), cend(ss), ostream_iterator<int>(cout, " "));
}
The output is:
77 77 77 77 77
Just use the fill_n() method.
Example
int n;
cin>>n;
int arr[n];
int value = 9;
fill_n(arr, n, value); // 9 9 9 9 9...
Learn More about fill_n()
or
you can use the fill() method.
Example
int n;
cin>>n;
int arr[n];
int value = 9;
fill(arr, arr+n, value); // 9 9 9 9 9...
Learn More about fill() method.
Note: Both these methods are available in algorithm library (#include<algorithm>). Don't forget to include it.
Starting with C++11 you could also use a range based loop:
int directory[10];
for (auto& value: directory) value = -1;
Could one write a function that returns the number of elements in an enum? For example, say I have defined:
enum E {x, y, z};
Then f(E) would return 3.
Nope.
If there were, you wouldn't see so much code like this:
enum E {
VALUE_BLAH,
VALUE_OTHERBLAH,
...
VALUE_FINALBLAH,
VALUE_COUNT
}
Note that this code is also a hint for a (nasty) solution -- if you add a final "guard" element, and don't explicitly state the values of the enum fields, then the last "COUNT" element will have the value you're looking for -- this happens because enum count is zero-based:
enum B {
ONE, // has value = 0
TWO, // has value = 1
THREE, // has value = 2
COUNT // has value = 3 - cardinality of enum without COUNT
}
There are ways, but you have to work... a bit :)
Basically you can get it with a macro.
DEFINE_NEW_ENUM(MyEnum, (Val1)(Val2)(Val3 = 6));
size_t s = count(MyEnum());
How does it work ?
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/size.hpp>
#define DEFINE_NEW_ENUM(Type_, Values_)\
typedef enum { BOOST_PP_SEQ_ENUM(Values_) } Type_;\
size_t count(Type_) { return BOOST_PP_SEQ_SIZE(Values_); }
Note that length could also be a template specialization or anything. I dont know about you but I really like the expressiveness of a "Sequence" in BOOST_PP ;)
No, this is a VFAQ and the answer is NO!!
Not without kludging anyway.
Even that trick about with a final entry only works if none of the values are non-default. E.g.,
enum B {
ONE, // has value = 0
TWO, // has value = 1
THREE=8, // because I don't like threes
COUNT // has value = 9
}
No. For one thing, you can't take types as parameters (just instances of types)