Array Split in C++ - c++

I am trying to split an array, and this is how I am doing it:
int arr1[] = {1, 2, 3, 4, 5};
int *arr2 = arr1 + 1;
Now I need to do this in a loop. In every iteration, I am trying to decrease the size of the array by 1 element or 2 elements based on a condition. For obvious reasons I can't declare int arr2[some_variable] .
But I want a new array to be created in every iteration of the loop whose size is 1 less than its parent array. I am not sure how I can achieve this. Can anyone help please?
In Java, there is a function which can do this: int newArr[] = Arrays.copyOfRange(arr, 1, arr.length); I wanted something similar to this in C++.

Use std::vector<int> from the C++ standard library:
#include <string>
#include <iostream>
#include <vector>
void dump(std::vector<int> &v)
{
for (std::vector<int>::iterator it = v.begin(); it != v.end(); it++)
std::cout << *it << " ";
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a + 5);
std::vector<int> v2(v.begin() + 1, v.begin() + 4);
dump(v);
std::cout << std::endl;
dump(v2);
}
And if you really-really-really can't use vector (why, seriously?), then just memcpy.
int arr[] = { 1, 2, 3, 4, 5 };
int cp[3];
memcpy(cp, arr + 1, sizeof(cp));

I'm not sure exactly why you want to have a new one each time, but you can use a standard container, like std::vector:
std::vector<int> arr1{1, 2, 3, 4, 5}; //std::iota is another option
int index{};
/*loop header*/ {
//make sure arr1.size() is at least 1
std::vector<int> arr2(std::next(std::begin(arr1), ++index), std::end(arr1));
}
I use std::next because it works in more scenarios. All this does is create a vector from two iterators: as far past the beginning as necessary, and the end (one past because it's exclusive).
Though C++11 is nice, it's not always a reality. In that case, this should work:
int arr1temp[] = {1, 2, 3, 4, 5};
std::vector<int> arr1(arr1temp, arr1temp + sizeof(arr1temp)/sizeof(arr1temp[0]));
int index = 0;
/*loop header*/ {
//make sure arr1.size() is at least 1
std::vector<int>::iterator start = arr1.begin();
std::advance(start, ++index);
std::vector<int> arr2(start, arr1.end());
}

/why/ do you think you need to make a copy of the array? Pointers and arrays are somewhat interchangeable, so all you need to do is track size and modify that.
void doSomethingWithArray(int* array, size_t arraySize) {
....
}
const size_t arraySize = 5;
int arry1[arraySize] = { 1, 2, 3, 4, 5 };
int* array = arr1;
int* arrayEnd = arr1 + arraySize;
for (int i = 0; i < 10; ++i) {
if ((*array) & 1 == 1) {
array += 1;
} else {
array += 3;
}
if(array >= arrayEnd)
break;
size_t howBigIsMySlice = arrayEnd - array;
if(howBigIsMySlice > && (rand() % 1) == 0)
howBigIsMySlice -= 1;
doSomethingWithArray(array, howBigIsMySlice);
}
You made no copies of data, and as far as "doSomethingWithMyArray" is concerned, the array is as big as we tell it.

Related

How do I append 10 arrays to form a single array in c++?

Let's say I have these 10 previously declared arrays in my code.
int arr1[] = {1,2,3,4,5,6,7,8,9,10};
int arr2[] = {1,2,3,4,5,6,7,8,9,10};
int arr3[] = {1,2,3,4,5,6,7,8,9,10};
int arr4[] = {1,2,3,4,5,6,7,8,9,10};
int arr5[] = {1,2,3,4,5,6,7,8,9,10};
int arr6[] = {1,2,3,4,5,6,7,8,9,10};
int arr7[] = {1,2,3,4,5,6,7,8,9,10};
int arr8[] = {1,2,3,4,5,6,7,8,9,10};
int arr9[] = {1,2,3,4,5,6,7,8,9,10};
int arr10[] = {1,2,3,4,5,6,7,8,9,10};
Basically, I want to append all 10 of these arrays one after another to make one single array.
ArrayOfArrays = { arr1[], arr2[], arr3[], arr4[], arr5[], arr6[], arr7[], arr8[], arr9[], arr10[] }
How would I go about doing this? This question might seem trivial for some, but I'm new to C++ and can not figure out how to do it. Please help and thanks in advance.
Basically, I want to append all 10 of these arrays one after another to make one single array.
You cannot do that.
The closest you can get to that is by using std::array.
std::array<int, 10> arr1 = {1,2,3,4,5,6,7,8,9,10};
...
std::array<int, 10> arr10 = {1,2,3,4,5,6,7,8,9,10};
std::array<std::array<int, 10>, 10> arrayOfArray = {arr1, ..., arr10};
Try this approach:
#include <iostream>
#include <vector>
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int arr2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// ...other arrays here...
// We pass a reference to a vector and return the same vector for performance reasons.
// Compiler often can optimize that into a better code.
std::vector<int> append(std::vector<int> & vec, int * data, int size)
{
for (int i = 0; i < size; ++i)
vec.push_back(data[i]);
return vec;
}
int main()
{
std::vector<int> data;
data = append(data, arr1, 10);
data = append(data, arr2, 10);
for (auto i : data)
std::cout << i << ", ";
std::cout << std::endl;
return 0;
}
Also, in C++ there are good containers for storing arrays, try searching for std::array and std::vector containers. First is a fixed size static array, the other one is dynamic.
I want to append all 10 of these arrays one after another to make one
single array ?
You can have array of pointers like
int *ArrayOfPointers[10] = { &arr1, &arr2, &arr3, &arr4, &arr5, &arr6, &arr7, &arr8, &arr9, &arr10};
Here ArrayOfPointers is array of 10 int pointers i.e it can store address of 10 one dimension int array like arr1, arr2 etc.
I assume there may be better method than what I'm suggesting in advance C++ for the same task.
In C++ it is unnecessary and ill-advised to use C-style arrays. For arrays of
constant size you may use std::array
and for arrays of variable size, std::vector
It looks rather as if what you actually want is a constant two-dimensional matrix
and to be able to access each of its rows as as a constant array, but do not
know how to initialise a two-dimensional matrix. If that's the case, here's how:
#include <iostream>
#include <array>
std::array<std::array<int,10>,10> matrix = {{
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}}
}};
int main()
{
std::array<int,10> const & arr0 = matrix[0];
for (int const & i : arr0) {
std::cout << i << ' ';
}
std::cout << std::endl;
// Or more simply...
auto const & arr5 = matrix[5];
for (auto const & i : arr5) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
Compile, link and run:
$ g++ -Wall -Wextra main.cpp && ./a.out
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
live demo

How to remove every second value from a C++ array without making a copy of the array?

Problem: I want to get an array A[6] = {6, 5, 4, 3, 2, 1} to be A[6] = {5, 3, 1, 1, 1, 1}. In other words - "delete" every second value starting with 0th and shift all other values to the left.
My Attempt:
To do that I would use this code, where a - length of the relevant part of an array A (the part with elements that are not deleted), ind - index of the value that I want to delete.
for (int j = ind; j < n; j++)
A[j] = A[j+1];
However, I couldn't get this to work, using the code like that:
void deleting(int A[], int& a, int ind){
for (int j = ind; j < a; j++)
A[j] = A[j+1];
a--;
}
int A[6] = {6, 5, 4, 3, 2, 1};
a = 6
for (int i = 0; i < a; i+=2)
deleting(A, a, i);
After running this code I was getting A[6] = {5, 4, 2, 1, 1507485184, 1507485184}. So, it deleted the elements at indexes 0, 3. Why did it delete the 3rd index?
There are two ways to do this:
walk the array, copying the last n-i elements forward one place for every even i, or
figure out the eventual state and just go straight to that. The eventual state is the first n/2 places are array[i]=array[2*i + 1], and the last n/2 places are just copies of the last element.
The first method is what you asked for, but it does multiple redundant copy operations, which the second avoids.
As for your implementation problems, examine what happens when j=n-1, and remember A[n] is not a valid element of the array.
I suggest making the copy-everything-forward operation its own function anyway (or you can just use memcpy)
For these kinds of problems (in-place array manipulation), it's a good idea to just keep an index or pointer into the array for where you are "reading" and another where you are "writing." For example:
void odds(int* a, size_t len) {
int* writep = a;
int* readp = a + 1;
while (readp < a + len) { // copy odd elements forward
*writep++ = *readp;
readp += 2;
}
while (writep < a + len - 1) { // replace rest with last
*writep++ = a[len - 1];
}
}
Just for kicks, here is a version which doesn't use a loop:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <utility>
#include <initializer_list>
template <typename T, std::size_t Size>
std::ostream& print(std::ostream& out, T const (&array)[Size]) {
out << "[";
std::copy(std::begin(array), std::end(array) -1,
std::ostream_iterator<T>(out, ", "));
return out << std::end(array)[-1] << "]";
}
template <std::size_t TI, std::size_t FI, typename T, std::size_t Size>
bool assign(T (&array)[Size]) {
array[TI] = array[FI];
return true;
}
template <typename T, std::size_t Size,
std::size_t... T0>
void remove_even_aux(T (&array)[Size],
std::index_sequence<T0...>) {
bool aux0[] = { assign<T0, 2 * T0 + 1>(array)... };
bool aux1[] = { assign<Size / 2 + T0, Size - 1>(array)... };
}
template <typename T, std::size_t Size>
void remove_even(T (&array)[Size]) {
remove_even_aux(array, std::make_index_sequence<Size / 2>());
}
int main() {
int array[] = { 6, 5, 4, 3, 2, 1 };
print(std::cout, array) << "\n";
remove_even(array);
print(std::cout, array) << "\n";
}
If C++ algorithms are an option, I tend to prefer them by default:
auto *const end_A = A + (sizeof(A)/sizeof(*A));
auto *new_end = std::remove_if(
A, end_A,
[&A](int const& i) { return (&i - A) % 2 == 0; });
// Now "erase" the remaining elements.
std::fill(new_end, end_A, 0);
The std::remove_if algorithm simply moves the elements that do not match the predicate (in our case, test if the address is MOD(2)=0), and std::moves them to the end. This is in place. The new "end" is return, which I then indexed over and set the elements to 0.
So if it has to be an array the solution would be like this:
void deleting(int A[size], int size){
for (int i = 0; i < size / 2; i++)
A[i] = A[2 * i + 1];
for (int i = size / 2; i < size; i++)
A[i] = A[size / 2];
}
You first loop through first half of the array "moving" every second number to the front, and then you loop through the rest filling it with the last number.
For a more versatile version of other's answers:
#include <iostream>
template<typename InputIt, typename T>
void filter(InputIt begin, InputIt end, T const& defaultvalue)
{
InputIt fastforward = begin;
InputIt slowforward = begin;
fastforward++; // starts at [1], not [0]
while (fastforward < end)
{
*slowforward = *fastforward;
++slowforward;
++ ++fastforward;
}
while (slowforward < end) // fill with default value
{
*slowforward++ = defaultvalue;
}
}
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
std::cout << "before: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
filter(A, A+6, 1);
std::cout << "after: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
}
Outputs:
before: 6, 5, 4, 3, 2, 1,
after: 5, 3, 1, 1, 1, 1,
And this works with std::array<bool>, std::vector<std::string>, std::unordered_set<void*>::iterator, etc.
The common way of doing this would be keeping two indices: one to the entry you're modifying and the other to the entry you intend to process
const auto size = sizeof(A) / sizeof(int);
// N.b. if size == 1 entire array is garbage
int i = 0;
for (int nv = 1; nv < size; ++i, nv += 2)
A[i] = A[nv];
--i;
// Significative array is now [0;N/2[, fill with last now
for (int j = i + 1; j < size; ++j)
A[j] = A[i];
This grants an in-place-modify fashion.
you can combine std::remove_if and std::fill to do this
example code:
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
auto endX = std::remove_if(std::begin(A),std::end(A),[&A](const int& i){return (&i-A)%2==0;});
if(endX!=std::begin(A))//in case nothing remained, although not possible in this case
std::fill(endX,std::end(A),*(endX-1));
//else /*something to do if nothing remained*/
for(auto a : A)std::cout<<a<<' ';
}

array copy reversal in c++

Is there a way to copy an array to another way in reverse order by using a while loop in c++??
I'm pretty sure I know how to do one with a for loop, but I'm curious if anyone knows of a way by using a while loop
Why not something like this?
#include <algorithm>
int src[] = {1, 2, 3, 4, 5};
int dst[5];
std::reverse_copy(src, src+5, dst);
int anArray = {1, 2, 3, 4, 5};
int reverseArray[5];
int count = 4;
int place = 0;
while(place < 5) {
reverseArray[place] = anArray[count];
count--;
place++;
}
As you said that you have done using for loop, you can follow following steps to convert it to while loop.
for(int i = sizeof(arr) - 1; i >= 0; i--)
{
// your logic
}
now convert it to,
int i = sizeof(arr);
for(; i >= 0; )
{
// your logic
i--;
}
simply replace for with while and remove ; within the braces.
int i = sizeof(arr);
while(i >= 0)
{
// your logic
i--;
}
You can use std::reverse for reversing the same array and std::reverse_copy for reversing to another output array as:
int main() {
int a[]= {1,2,3,4,5,6,7,8,9,10};
const int size = sizeof(a)/sizeof(int);
int b[size];
//copying reverse to another array
reverse_copy(a, a + size, b);
cout << "b = {";
copy(b, b + size, ostream_iterator<int>(cout, ", "));
cout << "}" << endl;
//reverse the same array
reverse(a, a + size);
cout << "a = {";
copy(a, a + size, ostream_iterator<int>(cout, ", "));
cout << "}" << endl;
return 0;
}
Output:
b = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, }
a = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, }
Demo : http://www.ideone.com/Fe5uj
There's been a few questions similar to this recently. I wonder if it is homework or an interview question somewhere. Here's one answer:
#define ELEMENT_COUNT(a) (sizeof((a))/sizeof((a)[0]))
int anArray[] = { 1, 2, 3, 4, 5 };
int reverseArray[ELEMENT_COUNT(anArray)];
int n = ELEMENT_COUNT(anArray);
int i = 0;
while(n--)
reverseArray[i++] = anArray[n];
I think it might be probing to see if you understand when expression like i++ and n-- are evaluated.

How do I find a particular value in an array and return its index?

Pseudo Code:
int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;
x = find(3).arr ;
x would then return 2.
The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).
To find the index, use std::distance and std::find from the <algorithm> header.
int x = std::distance(arr, std::find(arr, arr + 5, 3));
Or you can make it into a more generic function:
template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.
In your case, you would use it like so:
size_t x = index_of(arr, arr + 5, 3);
Here is a very simple way to do it by hand. You could also use the <algorithm>, as Peter suggests.
#include <iostream>
int find(int arr[], int len, int seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int x = find(arr,5,3);
std::cout << x << std::endl;
}
The fancy answer:
Use std::vector and search with std::find
The simple answer
Use a for loop
If the array is unsorted, you will need to use linear search.
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.
int arr[5] = {4, 1, 3, 2, 6};
vector<int> vec;
int i =0;
int no_to_be_found;
cin >> no_to_be_found;
while(i != 4)
{
vec.push_back(arr[i]);
i++;
}
cout << find(vec.begin(),vec.end(),no_to_be_found) - vec.begin();
We here use simply linear search. At first initialize the index equal to -1 . Then search the array , if found the assign the index value in index variable and break. Otherwise, index = -1.
int find(int arr[], int n, int key)
{
int index = -1;
for(int i=0; i<n; i++)
{
if(arr[i]==key)
{
index=i;
break;
}
}
return index;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int x = find(arr ,n, 3);
cout<<x<<endl;
return 0;
}
You could use the STL algorithm library's find function provided
#include <iostream>
#include <algorithm>
using std::iostream;
using std::find;
int main() {
int length = 10;
int arr[length] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int* found_pos = find(arr, arr + length, 5);
if(found_pos != (arr + length)) {
// found
cout << "Found: " << *found_pos << endl;
}
else {
// not found
cout << "Not Found." << endl;
}
return 0;
}
There is a find(...) function to find an element in an array which returns an iterator to that element. If the element is not found, the iterator point to the end of array.
In case the element is found, we can simply calculate the distance of the iterator from the beginning of the array to get the index of that element.
#include <iterator>
using namespace std;
int arr[ 5 ] = { 4, 1, 3, 2, 6 }
auto it = arr.find(begin(arr), end(arr), 3)
if(it != end(arr))
cerr << "Found at index: " << (it-begin(arr)) << endl;
else
cerr << "Not found\n";

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;
}