Every n element of an array in C++ - c++

Are there more efficient methods of getting every second (every N in general) element of an array then the simple for loop below? For example with the use of generic algorithms?
#include<iostream>
using namespace std;
int main()
{
const int a_size = 6, b_size = 3;
int a[a_size] = {1, 3, 6, 3, 2, 7};
int b[b_size];
int bx = 0;
for ( int ax = 0; ax < a_size; ++ax )
{
if (ax % 2 == 0)
b[bx++] = a[ax];
}
}

for (int ax = 0; ax < a_size; ax += 2)
Just be careful if a_size is close to INT_MAX.

A loop should be good enough. As Pete pointed out, you can avoid the modulo test.
for (int ax = 0; ax < a_size; ax += 2)
...
C++ offers support for slicing via the valarray header (e.g., take a look at std::slice_array).
I don't know if that is what you are looking for. It is intended for heavyweight numeric computations. If you are unsure, I think the simple loop is the right answer.

If by efficient, you mean faster with a smaller memory footprint, then I would opt to use pointers instead of array access. For example, what you want can be implemented in the following way with pointers.
int main() {
const int a_size = 6, b_size = 3;
int a[a_size] = {1, 3, 6, 3, 2, 7};
int b[b_size];
int* a_ptr = a;
int* a_end_ptr = a_ptr + a_size;
int* b_ptr = b;
while(a_ptr < a_end_ptr) {
*b_ptr = *a_ptr;
b_ptr++;
a_ptr += 2;
}
}
This example should be slightly faster than the array access examples and I encourage you to time it and see for yourself. However one thing you should always be aware of when making these optimizations is to look at whether it matters in the large scheme of the program (don't spend time when you don't have to).

You could easily create a every_n predicate and use that to filter as desired for copy_if, etc. That's as generic as you can get.
Approximate (note: untested as of yet) example of an "every n elements" predicate:
/**
#brief Un predicado que retorna #c true cada #a n invocaciones.
**/
template <typename Integer>
struct every_n {
static_assert (std::numeric_limits<Integer>::is_integer, "Must behave like an integer");
public:
explicit every_n (Integer const& e)
: n(e), x(1) {}
every_n (every_n const& E)
: n(E.n), x(E.x) {}
bool operator () (...) {
if (x<n) { ++x; return false; }
else { x=Integer(1); return true; }
}
private:
Integer x;
const Integer n;
};
// "make_" idiom
template <typename Integer>
every_n<Integer> every (Integer const& c) { return every_n<Integer>(c); }
// sample usage
# include required headers, etc
using namespace std;
const int a_size = 6, b_size = 3;
int a[a_size] = {1, 3, 6, 3, 2, 7};
int b[b_size];
copy_if (begin(a), end(a), begin(b), every(3));
All the code requires is that every() is called with a type that behaves like an integer.
(The code uses static_assert, begin(), end() and copy_if(), which are C++11, but functions just as well in C++03 if you backport the adequate functions, as I have)

This is as fast as it gets:
void copy_n(int & a[], int & b[], int a_sz, int n) {
int bx = 0;
for (int i=0; i<a_sz; i+=n) {
b[bx++]=a[i];
}
}

Example:
#include<iostream>
using namespace std;
int main() {
const int a_size = 6;
const int b_size = a_size / 2;
int a[a_size] = {1, 3, 6, 3, 2, 7};
int b[b_size];
for (int ax = 0, bx = 0; ax < a_size; ax += 2) {
b[bx++] = a[ax];
}
}

Related

Copying one int array to another C++

Was trying to write a program which converts the value`s from one assigned array to another unassigned one. The code i wrote:
#include "stdafx.h";
#include <iostream>;
using namespace std;
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int j[10];
int copy_array(int *p1, int n);
int *p2, *p2;
int main() {
for (int l = 0; l < 10; l++) {
cout << a[l] << endl;
}
copy_array(a, 10);
for (int i = 0; i < 10; i++) {
j[i] = &p2;
cout << j[i] << endl;
}
system("PAUSE");
return 0;
}
int copy_array(int *p1, int n) {
while (n-- > 0) {
*p1 = *p2;
*p1++;
*p2++;
}
}
Im using the Microsoft visual studio platform and the error i got was "There is no context in which this conversion is possible". Why i cant use this int convert path? how can i fix and connect the 2 arrays using int type conversion(if its possible)?
What i tried was manipulating the local function copy_array so it makes the conversion using the addresses of the j[10] array integers, but this gave me another error. Any support and advice would be appreciated.
These are some notes on your code:
you have redundant p2 declaration:int *p2, *p2;. Also you need to initialize it. so make it: int *p2 = j; (in fact, you don't actually need to use this global variable - you can achieve the same effect by passing j as necessary).
Inside your copy function, your assignment should be in reverse:
*p2 = *p1; not *p1 = *p2; - the right-hand side is assigned to the left hand side.
When printing j, you do not need j[i] = &p2; which alters j's contents.
It is better to define the arrays inside the function not in the general scope.
Correct them and your code should work fine.
However, You do not need pointers to do this at all.
Consider the following code and compare it to yours:
#include <iostream>
using namespace std;
void copy_array(int [], int [], int);
void print_array(int [], int);
int main() {
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int j[10];
print_array(a,10);
copy_array(a, j, 10);
print_array(j,10);
return 0;
}
void copy_array(int s[], int d[], int n) {
for (int i = 0; i < n; i++)
d[i] = s[i];
} // s for source & d for destination
void print_array(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n\n";
}
You don't need p2 to be global.
Just add parameter to copy_array.
like this:
void copy_array(int *p1, int *p2, int n) {
while (n-- > 0) {
*p1 = *p2;
p1++;
p2++;
}
}
and call like this:
copy_array(j, a, 10);
Also: to print the copy you just do:
for (int i = 0; i < 10; i++) {
cout << j[i] << endl;
}
I want to build on #Shadi's answer, which you should upvote, and make the code more C++-idiomatic.
In C++, we don't need to explicitly return 0; from main; it is implied, if you haven't returned anything else.
It's better to use names in a similar scheme for similar variables. Specifically, i and j are common variable names for integer scalars, e.g. counters - not arrays. I'd suggest you use a and b for the arrays, or values and copy_of_values etc.
The C++ standard library has an array-like container class named std::vector. It's not exactly the same as an array; for example, it uses dynamically-allocated memory, and can grow or shrink in size. The reason you might want to use it is that it allows you to perform plain assignment, and use other standard library facilities with it.
Thus Shadi's program becomes:
#include <iostream>
#include <vector>
void print_vector(const std::vector<int>& vec);
int main() {
std::vector<int> a { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> b;
print_vector(a);
b = a;
print_vector(b);
}
void print_vector(const std::vector<int>& vec) {
// this next line uses syntax from the 2011 version of
// the C++ language standard ("C++11").
for(int x : vec) {
std::cout << x << " ";
}
std::cout << "\n\n";
}
You can also avoid the loop in print_vector entirely, using std::for_each or std::for_each_n, but that would require some knowledge of iterators and lambda functions, which may be a bit advanced for a beginner, so I won't go into that. But better yet, you could define a out-streaming operator for std::vector's, as seen here, with which you could write std::cout << a; and have that work.

Using arithmetic with arrays

Two quantities u and v are said to be at right angles if
nuv = u1v1 + u2v2 + u3v3 + u4v4 +………… + unvn = 0
Write a function that computes whether u and v are at right angles. You may use arrays if you wish. The function can assume that the vectors have the same dimension (n, say), but this number should be passed as a parameter to the function.
I have a few errors in my program. I'd appreciate some help, as I'm a beginner. The errors are telling me:
In function 'void function(int*,int*)'
cpp 26: error expected ';' before '}' token
cpp 29: error ;value required as left operand of assignment
#include <iostream>
using namespace std;
const int n = 5;
void function(int array[n],int array2[n]);
int main(){
int array[n] = {5, 3 , -4, 2, 8};
int array2[n] ={-7, -9, 5, 2, 9};
function(array, array2);
return 0;
}
void function(int array[n], int array2[n]){
int multiple;
for(int i=0; i <=5, i++)
{
(array[i]*array2[i]) + (array[i+1]*array2[i+1]) = multiple;
}
cout << multiple << endl;
}
Your for loop is malformed. You need to use < instead of <=, use n instead of 5, and use ; instead of ,.
Your assignment of multiple is backwards. The value on the right-side of the = operator is assigned to the variable on the left-side of =. You are trying to assign the value of multiple (which is uninitialized) to a dynamically computed value that has no explicit variable of its own. You should be assigning the computed value to multiple instead.
Also, you didn't follow the "this number [array dimensions] should be passed as a parameter to the function" requirement of your instructions.
Try this:
#include <iostream>
using namespace std;
const int n = 5;
void function(const int *array1, const int *array2, const int size);
int main()
{
int array1[n] = { 5, 3, -4, 2, 8};
int array2[n] = {-7, -9, 5, 2, 9};
function(array1, array2, n);
return 0;
}
void function(const int *array1, const int *array2, const int size)
{
int multiple = 0;
for(int i = 0; i < size; i++)
{
multiple += (array1[i] * array2[i]);
}
cout << multiple << endl;
}
Syntax error is where you are using the for loop in this fashion:
for(int i=0;i<=5,i++)
Use this instead:
for(int i=0; i <= 5; i++)
The function can assume that the vectors have the same dimension (n,
say), but this number should be passed as a parameter to the
function.
This function declaration
void function(int array[n],int array2[n]);
does not include a parameter that specifies the dimension of the arrays.
The above declaration is equivalent to
void function(int *array,int *array2);
because arrays passed by value are implicitly converted to pointers to their first elements.
There are a typo and a bug in this for statement
for(int i=0; i <=5, i++)
^^^^^^
There shall be
for ( int i=0; i < n; i++)
The variable multiple
int multiple;
is not initialized and this assignment
(array[i]*array2[i]) + (array[i+1]*array2[i+1]) = multiple;
does not have sense and has nothing common with the condition
nuv = u1v1 + u2v2 + u3v3 + u4v4 +………… + unvn = 0
It seems what you mean is the following
#include <iostream>
bool function( const int array[], const int array2[], size_t n )
{
long long int product = 0;
for ( size_t i = 0; i < n; i++)
{
product += array[i] * array2[i];
}
return product == 0;
}
int main()
{
const size_t N = 5;
int array[N] = { 5, 3 , -4, 2, 8 };
int array2[N] = { -7, -9, 5, 2, 9 };
std::cout << "array and array2 are "
<< (function(array, array2, N) ? "" : "not ")
<< "at right angles"
<< std::endl;
return 0;
}
These arrays
int array[N] = { 5, 3 , -4, 2, 8 };
int array2[N] = { -7, -9, 5, 2, 9 };
are not a right angles,
But these arrays
int array[N] = { 5, 3 , -4, 1, 9 };
int array2[N] = { -7, -9, 5, 1, 9 };
are at right angles. Try them.
Alternative: try the C++ way. Use std::array that knows it's length. Use algorithms provided by the standard library like std::inner_product.
#include <iostream>
#include <algorithm>
#include <array>
#include <numeric>
int main()
{
using arr_t = std::array<int,5>;
arr_t arr1 = {5, 3 , -4, 2, 8};
arr_t arr2 = {-7, -9, 5, 2, 9};
int mult = std::inner_product( begin(arr1), end(arr1), begin(arr2), 0,
std::plus<>(), std::multiplies<>() );
std::cerr << mult << "\n";
}

How do I stop my array from printing address?

I have a header, cpp and main class.
//Arr.h
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
//Arr.cpp
#include "Arr.h"
#include <iostream>
using namespace std;
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
However, when I run the code, a.printArr() prints out array address and not the values contained in the array. Is there a way to fix this?
Your code will print not address but some indeterminate value generated via default-initializing. Initialize the member array instead of the local array to throw away.
void Arr::setArr()
{
x[0] = 2;
x[1] = 3;
x[2] = 5;
x[3] = 7;
x[4] = 11;
}
Your problem is here:
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
the declaration int x[5] defines a new array of 5 elements which will be destroyed on exiting that function; and the name x hides the data member Arr::x.
One way you can do it is this:
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
Full code:
#include <iostream>
#include <algorithm>
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
using namespace std;
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
Your code is not printing array address. Maybe you saw some unexpected numbers and assumed it was an address, but in fact it is undefined behaviour caused by outputting uninitialized variables.
Your code int x[5] = .... failed because this declares a new local variable x, it doesn't modify the class member x.
Perhaps you tried:
x = { 2, 3, 5, 7, 11 };
and got compilation errors. This is because C-style arrays may not be assigned. This annoying rule is a hangover from C++'s past. To avoid this problem and many others, you can try to avoid using C-style arrays. In this case use a C++ array:
private:
std::array<int, 5> x;
Then the suggested assignment will work.
As WhiZTiM has already pointed out, your problem is at the setArr function in your class. The reason for this is because in C++ you cannot assign values to the array in the "normal fashion" i.e. using x = {blah, blah, blah}; (unless you use std::array<int, ARRAYSIZE>). In setArr you are creating another array named x and then this array is deleted once it is out of scope, and in printArr you are printing an array with no values in it yet.
Each value in the array must be set individually in C styled arrays (as shown in MikeCAT's answer).
One solution to this is to create a temporary array with the values you want and assigning the values to your class array through a for loop, i.e.:
void Arr::setArr() {
const int ARRAYSIZE = 5;
int tmp[ARRAYSIZE] = {2, 3, 5, 7, 11};
for (int i = 0; i < ARRAYSIZE; ++i) {
x[i] = tmp[i];
}
}
As M.M also pointed out, can simply change int x[5] in your private variables in Arr to std::array<int, 5> x and then in setArr simply have the statement: x = {2, 3, 5, 7, 11}; which is the better option in my opinion and easier to read, but it's also good to know how to use C arrays 😊

Virtual concatenation with arrays

Suppose I have 3 double precision arrays a1[], a2[], a3[] each of length L1, L2, L3
Suppose I want to concatenate these arrays "virtually" That is I want to create a virtual
array a_virtual[] such that a_virtual = {a1[L1], a2[L2], a3[L3]} logically, though physically these arrays may not be contiguous to each other.
So if I want to access a_virtual[5] and L1=2, L2=3, L3=1 then a3[0] will be fetched. For accessing a_virtual[0], a1[0] will be fetched
How would I do this
in C
in C++ (how to do this with std::vectors in place of arrays would
also be useful)
in CUDA
I suspect if there is a way to do it, it would be the same for all the three environments, but there might be more efficient ways to do this within each environment depending on the
capabilities provided.
Here's a possible solution in C, using linked-list and (tail) recursion:
#include <stdio.h>
struct dblarr {
double *data;
size_t len;
struct dblarr *next;
};
double *fetch(const struct dblarr *arr, size_t index) {
if (arr == NULL) return NULL;
if (index < arr->len) return arr->data + index;
return fetch(arr->next, index - arr->len);
}
int main(void) {
double a1[2] = {1, 2};
double a2[3] = {1, 2, 3};
double a3[1] = {1};
struct dblarr x1, x2, x3;
x1.data = a1; x1.len = sizeof a1 / sizeof *a1; x1.next = &x2;
x2.data = a2; x2.len = sizeof a2 / sizeof *a2; x2.next = &x3;
x3.data = a3; x3.len = sizeof a3 / sizeof *a3; x3.next = NULL;
printf("before %f\n", *fetch(&x1, 5));
*fetch(&x1, 5) = 0.42;
printf(" after %f\n", *fetch(&x1, 5));
return 0;
}
You can "see the code running" at http://ideone.com/mY0ix.
How about something like the following? It's pretty hard-coded and not the best/ cleanest code, but maybe you can generalize this logic?
#include <iostream>
#include <vector>
using namespace std;
void logicalConcat(vector<int>& a1, vector<int>& a2, vector<int>& a3, int k) {
if(k > a1.size() - 1)
k -= a1.size();
else {
cout << a1[k] << endl;
return;
}
if(k > a2.size() - 1)
k -= a1.size();
else {
cout << a2[k] << endl;
return;
}
cout << a3[k] << endl;
}
Here k would be the index of the the virtual concatenation you want. We're not concatenating anything, just iterating over the vectors.
If the arrays need not be contiguous, then one way to do it is to convert a single index into two indices, one for an array of pointers to the real arrays, and another for the array that has the desired element.
To do this, you would create an array of pointers to those arrays:
double** arrays = {a1, a2, a3};
then an array of their lengths:
int arraysizes = { sizeof(a1) / sizeof(*a1), sizeof(a2) / sizeof(*a2), sizeof(a3) / sizeof(*a3) };
Then, given an index n, you can calculate the two indices for arrays by doing
int i1 = 0, j = 0;
while (n - arraysizes[j] >= 0)
n -= arraysizes[j++], ++i1;
And you can then index the array of pointers like this to get the actual element:
arrays[n][i2]
You could also create a wrapper class to do this arithmetic with a built in operator[].
Some of the others provide an answer for a basic C implementation.
Here is some sample code for a general-purpose c++ implementation of a class which creates virtual concatenated arrays without copying any of the array elements. Once created, the virtual array can be indexed like an ordinary vector (to be read or written to):
#include <vector>
#include <map>
#include <iostream>;
using namespace std;
class VirtualArray {
public:
multimap<int,double*> startIndices; // reverse map of starting index to its sub array
int size;
VirtualArray() : size(0) {}
double & operator[](int i) {
// find proper subarray in log(n) time
multimap<int,double*>::iterator iter = --startIndices.upper_bound(i);
double *subarray = iter->second;
int startIndex = iter->first;
// index into subarray
return subarray[i-startIndex];
}
void addArray(double* array, int length) {
startIndices.insert(make_pair(size, array));
size += length;
}
void addVector(vector<double> & vec) {
startIndices.insert(make_pair(size, vec.data()));
size += vec.size();
}
};
int main() {
double a1[3], a2[4], a3[6] = {1, 2, 3, 4, 5, 6};
int L1 = 3, L2 = 4, L3 = 6;
vector<double> a3vec;
a3vec.assign(a3,a3+6);
VirtualArray vArray;
vArray.addArray(a1,L1);
vArray.addArray(a2,L2);
vArray.addVector(a3vec);
cout << vArray[10];
return 0;
}

How to get distinct values from an arrays of different sizes?

Q:
arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9}
Ans:
values[]={1,2,5,6,7,9}
Q:
arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9}
Ans:
values[]={1,2,5,6,7,9,101,1502}
here is what i tried but not working
for(int i=0;i<(index-1);i++) {
if(data[i].age != data[i+1].age) {
c=new list;
c->value=data[i].age;
c->next=NULL; clas++;
if(age_head==NULL) {
p=c; age_head=c;
}
for(c=age_head;c!=NULL,c->next!=NULL;p=c,c=c->next) {
if(data[i].age!=c->value)
found=false;
else
found=true;
}
if((age_head!=NULL)&& (found=false)) {
p->next=c; c->next=NULL;
}
}
}
This is not the most efficient, but it has some values:
It uses STL objects
It uses a cool little known template trick for knowing at compile time the size of your C-like arrays
...
int a[] = {1,1,1,2,5,5,6,6,6,6,8,7,9} ;
int b[] = {1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9} ;
// function setting the set values
template<size_t size>
void findDistinctValues(std::set<int> & p_values, int (&p_array)[size])
{
// Code modified after Jacob's excellent comment
p_values.clear() ;
p_values.insert(p_array, p_array + size) ;
}
void foo()
{
std::set<int> values ;
findDistinctValues(values, a) ;
// values now contain {1, 2, 5, 6, 7, 8, 9}
findDistinctValues(values, b) ;
// values now contain {1, 2, 5, 6, 7, 8, 9, 101, 1502}
}
Another version could return the set, instead of taking it by reference. It would then be:
int a[] = {1,1,1,2,5,5,6,6,6,6,8,7,9} ;
int b[] = {1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9} ;
// function returning the set
template<size_t size>
std::set<int> findDistinctValues(int (&p_array)[size])
{
// Code modified after Jacob's excellent comment
return std::set<int>(p_array, p_array + size) ;
}
void foo()
{
std::set<int> valuesOne = findDistinctValues(a) ;
// valuesOne now contain {1, 2, 5, 6, 7, 8, 9}
std::set<int> valuesTwo = findDistinctValues(b) ;
// valuesTwo now contain {1, 2, 5, 6, 7, 8, 9, 101, 1502}
}
The first thing I spot in your code is
if((age_head!=NULL)&& (found=false)) {
you use assignment (=) instead of equality (==). The expression should be
if((age_head!=NULL)&& (found==false)) {
Then, in this loop
for(c=age_head;c!=NULL,c->next!=NULL;p=c,c=c->next) {
you are looking for a value in the list. However, in its current form, when the loop terminates, found will show whether the last element in the list equals to c->value. You need to check for found in the loop condition (and you need to AND the expressions instead of listing them separated by comma!):
for(c=age_head, found = false; !found && c!=NULL && c->next!=NULL; ...) {
The result of the comma operator is the result of the last subexpression inside - this is definitely not what you want. Moreover, with comma all subexpressions are evaluated, which results in dereferencing a null pointer if c == NULL - whereas the && operator is evaluated lazily, thus c->next!=NULL is evaluated only if c != NULL.
The next thing is that you need to search for the value in the list before you add it to the list! Also note that you are trying to check for two different things: that the actual data element is different from the next one, and that its value is not yet added to the list. The second condition is stronger - it will always work, while the first only works if the input data is ordered. So you can omit the first check altogether. The result of all the above, plus some more simplifications and clarifications, is
for(int i=0;i<index;i++) {
for(list* c=age_head, found=false; !found&&c&&c->next; p=c,c=c->next) {
if(data[i].age==c->value)
found=true;
}
if(!found) {
list* newc=new list;
newc->value=data[i].age;
newc->next=NULL;
clas++;
if(age_head==NULL) {
p=newc; age_head=newc;
} else {
p->next=newc; newc->next=NULL;
}
}
}
I still don't guarantee that your linked list handling logic is right though :-) In its current form, your code is hard to understand, because the different logical steps are not separated. With a bit of refactoring, the code could look a lot clearer, e.g.
for(int i=0;i<index;i++) {
if(!foundInList(data[i].age)) {
addToList(data[i].age);
}
}
Of course the simplest and most efficient would be using STL containers/algorithms instead, as shown in other answers. But I think there is much more educational value in improving your first attempt :-)
If the output need not to be sorted, you can use a Hashtable.
E.g. something like this:
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
#include <boost/unordered_set.hpp>
#include <vector>
using namespace std;
using namespace boost;
int main() {
int arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9};
size_t n = sizeof(arr1)/sizeof(int);
unordered_set<int> h;
for (size_t i = 0; i < n; ++i)
h.insert(arr1[i]);
vector<int> values;
foreach(int a, h)
values.push_back(a);
return 0;
}
The runtime is then in O(n).
An alternative to that is sorting the array and then to eliminate neighboring identical elements (advantage only STL is needed). But then the runtime is in O(n log n):
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9};
size_t n = sizeof(arr1)/sizeof(int);
sort(arr1, arr1+n);
int *end = unique(arr1, arr1+n);
vector<int> values(arr1, end);
return 0;
}
Easily done using STL.
int array[] = { 1, 1, 2, 2, 1, 3, 3, 4, 5, 4, 4, 1, 1, 2 };
int nElements = sizeof(array)/sizeof(array[0]);
std::sort(&array[0], &array[nElements]);
int newSize = std::unique(&array[0], &array[nElements]) - &array[0];
first you need to sort the array and than do something like this:
for(int i = 0; i < size -1; i++)
{
if(array[i]!=array[i+1])
unique++;
// store it wherever you want to.
stored.push(array[i]);
}
#include <vector>
#include <algorithm>
#include <iostream>
int
main ()
{
int array[] = { 1, 1, 2, 2, 1, 3, 3, 4, 5, 4, 4, 1, 1, 2 };
std::vector < int >values;
values.push_back (array[0]);
for (int i = 1; i < sizeof (array) / sizeof (int); ++i)
{
std::vector < int >::iterator it =
std::find (values.begin (), values.end (), array[i]);
if (it == values.end ())
values.push_back (array[i]);
}
std::cout << "Result:" << std::endl;
for (int i = 0; i < values.size (); i++)
std::cout << values[i] << std::endl;
}
This seems to be a duplicate of Removing duplicates in an array while preserving the order in C++
While the wording of the question is different, the result is the same.
Based on above ideas/codes, I am able to accomplish my job on finding distinct values in C++ array. Thanks every one who replied on this thread.
#include <set>
#include <iostream>
using namespace std;
// function setting the set values
template<size_t size>
void findDistinctValues(std::set<int> & p_values,int (&p_array)[size])
{
// Code modified after Jacob's excellent comment
p_values.clear() ;
p_values.insert(p_array, p_array + size) ;
}
void findDistinctValues2( int arr[],int size)
{
std::set<int> values_1 ;
std::set<int>::iterator it_1;
values_1.clear();
values_1.insert(arr,arr+size);
for (it_1=values_1.begin(); it_1!=values_1.end(); ++it_1)
std::cout << ' ' << *it_1<<endl;
}
int main()
{
int arr[] = {1,6100,4,94,93,-6,2,4,4,5,5,2500,5,4,5,2,3,6,1,15,16,0,0,99,0,0,34,99,6100,2500};
std::set<int> values ;
std::set<int>::iterator it;
int arr_size = sizeof(arr)/sizeof(int);
printf("Total no of array variables: %d\n",arr_size);
printf("Output from findDistinctValues (function 1)\n ");
findDistinctValues(values, arr) ;
for (it=values.begin(); it!=values.end(); ++it)
std::cout << ' ' << *it<<endl;
std::cout<<endl;
std::cout<<values.size()<<endl; //find the size of distict values
printf("Output from findDistinctValues (function 2) \n ");
findDistinctValues2(arr,arr_size);
getchar();
return 0;
}