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
}
Related
This question already has answers here:
Good C++ solutions to the "Bring all the zeros to the back of the array" interview challenge
(3 answers)
Closed 4 years ago.
I am working on this question:
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
I know how to answer this question by just doing in-place swapping, but I also would want to see if it is possible to solve it with std::sort.
According to cplusplus.com:
the comparator function for the sort function is a Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
//comments below are based on my understanding
static bool comp(int a, int b){
//lambda function evaluates to true - no swap,
//evaluates to false -swap
if(a==0) return false;
if(b==0) return true;
//if neither a nor b is 0 them do not swap
return true;
}
void moveZeroes(vector<int>& nums) {
sort(nums.begin(),nums.end(),comp);
}
the given test case is [0,1,0,3,12]
my output is [12,3,1,0,0]
You almost had it right. In your comparator function, you have to return false to not swap them. Also, change std::sort to std::stable_sort to keep the values in original order.
static bool comp(int a, int b)
{
//lambda function evaluates to true - no swap,
//evaluates to false -swap
if(a==0) return false;
if(b==0) return true;
//if neither a nor b is 0 them do not swap
return false;
}
void moveZeros(std::vector<int>& nums)
{
std::stable_sort(nums.begin(),nums.end(),comp);
}
LIVE DEMO
As Drew Dormann pointed out stable partition is the proper algorithm. Here is the code:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> data { 0, 1, 0, 3, 12 };
std::stable_partition(
data.begin(), data.end(), [](int n) { return n != 0; });
for (auto i : data)
cout << i << ' ';
cout << endl;
}
The output is 1 3 12 0 0
The sort order you want to use is simply that zeros are "greater" than all non-zero values, and equal to other zeros. All other non-zero values are "less" than zero, and are equivalent to any other non-zero value.
Construct the comparison function properly, then you can use it in a call to std::stable_sort to achieve what you're trying to do.
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';
Can someone please explain to me why the output from the following code is saying that arrays are not equal?
int main()
{
int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};
if (iar1 == iar2)
cout << "Arrays are equal.";
else
cout << "Arrays are not equal.";
return 0;
}
if (iar1 == iar2)
Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.
To do an element-wise comparison, you must either write a loop; or use std::array instead
std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};
if( iar1 == iar2 ) {
// arrays contents are the same
} else {
// not the same
}
Since nobody mentioned it yet, you can compare arrays with the std::equal algorithm:
int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};
if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
cout << "Arrays are equal.";
else
cout << "Arrays are not equal.";
You need to include <algorithm> and <iterator>. If you don't use C++11 yet, you can write:
if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))
You're not comparing the contents of the arrays, you're comparing the addresses of the arrays. Since they're two separate arrays, they have different addresses.
Avoid this problem by using higher-level containers, such as std::vector, std::deque, or std::array.
Array is not a primitive type, and the arrays belong to different addresses in the C++ memory.
Nobody mentions memcmp? This is also a good choice.
/* memcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n=memcmp ( buffer1, buffer2, sizeof(buffer1) );
if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);
return 0;
}
Ref: http://www.cplusplus.com/reference/cstring/memcmp/
If you are reluctant to change your existing code to std::array, then use a couple of methods instead which takes non-type template arguments :
//Passed arrays store different data types
template <typename T, typename U, int size1, int size2>
bool equal(T (&arr1)[size1], U (&arr2)[size2] ){
return false;
}
//Passed arrays store SAME data types
template <typename T, int size1, int size2>
bool equal(T (&arr1)[size1], T (&arr2)[size2] ){
if(size1 == size2) {
for(int i = 0 ; i < size1; ++i){
if(arr1[i] != arr2[i]) return false;
}
return true;
}
return false;
}
Here is the demo. Note that, while calling, we just need to pass the array variables e.g. equal(iar1, iar2) in your case, no need to pass the size of arrays.
You are comparing the addresses instead of the values.
Both store memory addresses to the first elements of two different arrays. These addresses can't be equal hence the output.
If you are willing to use std::array instead of built-in arrays, you may use:
std::array<int, 5> iar1 = {1,2,3,4,5};
std::array<int, 5> iar2 = {1,2,3,4,5};
if (iar1 == iar2)
Right. In most, if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (i.e. the first element's address). What you're doing here is comparing those addresses, which is obviously wrong.
Instead, you need to iterate over both arrays, checking each element against each other. If you get to the end of both without a failure, they're equal.
When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.
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 };
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;