GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #21  
Old 08-May-2008, 05:52
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Re: Deleting elements of arrays C++


Quote:
Originally Posted by the_crazyman
New to this and was after some help/direction.

I'm writing a program (new to C++). I've to open a file, read in 20 chars, sort it alphabetically and then remove any duplicates.

I can get it to read in, sort and display the sorted array, but I can't work out the deletion bit. Any advice?

The source code is below for the programs. Any algorithm that would help would be a massive weight off the shoulders:-

CPP / C++ / C Code:
void getLetters()
{

int count;

ifstream inputFile; // like declaring a variable
inputFile.open("A:letters.dat");

count = 0;


inputFile >> GetTwentyLetters[firstElement]; // priming read

while ( count != lastElement )
{
count++;
inputFile >> GetTwentyLetters[count];
}

char GetTwentyLetters = count;

inputFile.close(); // always close the file when done with it





}



void sortLetters() 
{
/********* PASS 1: SORTING THE ARRAY *********/
int i,j;
char temp;
// For each element in the array
for(i=lastElement; i>=0; i--) 
{ //For each pair of elements in the array) 
for(j=0; j<i; j++) 

{//At each location, compare the two adjacent elements

if(GetTwentyLetters[j] > GetTwentyLetters[j+1]) 
{ 
// Swap elements as needed
temp = GetTwentyLetters[j];
GetTwentyLetters[j] = GetTwentyLetters[j+1];
GetTwentyLetters[j+1] = temp;
}
} 
}

}

I presume I have to move all elements down 1 position if there is a duplicated pair? But how?
This is a very simple function that will help you to extract duplicate characters u can change the in put from cin to infile using the class fstream
CPP / C++ / C Code:
#include<iostream>
#include<string>
#include<xstring>
using namespace std;
void extract_Duplicate();
int main()
{
	extract_Duplicate();

return 0;
}
void extract_Duplicate()
{
string str;
cin>>str;
string temp;
temp=str[0];
int j=0;int i;
int b=str.length();

 for(i=0;i<str.length();i++)
 {
	if(str[j] != str[i])
	{
	j=i;
	temp=temp+str[j];
	b--;
	}
 }
	 cout<<temp<<endl;
}
  #22  
Old 08-May-2008, 05:57
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Re: Deleting elements of arrays C++


i am posting this code if any body can find a faster way for the complier to execute the extract function please let me know i am not that experienced with c++
CPP / C++ / C Code:
#include<iostream>
#include<string>
#include<xstring>
using namespace std;
void extract_Duplicate();
int main()
{
	extract_Duplicate();

return 0;
}
void extract_Duplicate()
{
string str;
cin>>str;
string temp;
temp=str[0];
int j=0;int i;
int b=str.length();

 for(i=0;i<str.length();i++)
 {
	if(str[j] != str[i])
	{
	j=i;
	temp=temp+str[j];
	b--;
	}
 }
	 cout<<temp<<endl;
}


  #23  
Old 28-May-2008, 06:42
VulturEMaN VulturEMaN is offline
New Member
 
Join Date: May 2008
Posts: 6
VulturEMaN is on a distinguished road

Re: Deleting elements of arrays C++


Alright.....ugh.

I have a similar problem, but with a (seemingly) complicated twist....

1. Instead of reading data in via a file, its being inputted by the user.
2. Not only does it remove the dupicates, it needs to keep a count of how many duplicates there were for that individual number.

for example:

If i put in

3 4 5 6 2 3 3 3 6

it would output

N Count
2 1
3 4
4 1
5 1
6 2

My first problem that I've run into is for some reason
(i'm a little whelmed at this point) is I can't figure out
how to get the count, or display only the reduced number
of values in the first array. Its my first experience with
arrays and this is crazy.

CPP / C++ / C Code:
#include <iostream>
using namespace std;

void fillArray(int a[], int& size, int& numberUsed);
//Array is filled with the number of variables equal to
//the value of size as long as size is less than 50.

void sort(int a[], int numberUsed);
//The values of a[0] through a[numberUsed - 1] have been
//rearranged so that a[0] <= a[1] <= ... <= a[numberUsed - 1].

void swapValues(int& v1, int& v2);
//Interchanges the values of v1 and v2.

int indexOfSmallest(const int a[], int startIndex, int numberUsed);
//Returns the index i such that a[i] is the smallest of the values
//a[startIndex], a[startIndex + 1], ..., a[numberUsed - 1].

int remove(int a[], int index, int& size);

int main( ){
  int sampleArray[50], a[50], b[50], size, numberUsed, lastElement;

  do{
  cout << "This program sorts numbers from lowest to highest.\n";
  cout << "Enter the size of the array (0-50): " << endl;
  cin >> size;
  } while (size > 50);

  fillArray(sampleArray, size, numberUsed);
  sort(sampleArray, numberUsed);

  cout << "In sorted order the numbers are:\n";
  for (int index = 0; index < numberUsed; index++){
    cout << sampleArray[index] << " ";
    cout << endl;
    }

  system("pause");

  remove(sampleArray, 0, numberUsed);

  cout << "beta output:\n";
  for (int index = 0; index < size; index++){
    cout << sampleArray[index] << " ";
    cout << endl;
    }

  system("pause");
  return 0;
}

void fillArray(int a[], int& size, int& numberUsed){
  cout << "Enter the " << size << " numbers in the array" << endl;
  for (int i=0; i<size; i++){
    cin >> a[i]; //adds the numbers to the array
    numberUsed = size;
    }
}

void sort(int a[], int numberUsed){
  int indexOfNextSmallest;
  for (int index = 0; index < numberUsed - 1; index++){//Place the correct value in a[index]:
    indexOfNextSmallest = indexOfSmallest(a, index, numberUsed);
    swapValues(a[index], a[indexOfNextSmallest]);
      //a[0] <= a[1] <=...<= a[index] are the smallest of the original array
      //elements. The rest of the elements are in the remaining positions.
    }
}

void swapValues(int& v1, int& v2){
  int temp;
  temp = v1;
  v1 = v2;
  v2 = temp;
}

int indexOfSmallest(const int a[], int startIndex, int numberUsed){
  int min = a[startIndex], indexOfMin = startIndex;
  for (int index = startIndex + 1; index < numberUsed; index++){
    if (a[index] < min){
      min = a[index]; //min is the smallest of a[startIndex] through a[index]
      indexOfMin = index;
      }
    }
  return indexOfMin;
}

int remove(int a[], int index, int& size){
  int b[50], j, i, lastElement = (size-1);
  for (i = 0; i <= size; i++){
    while (a[i] == a[i+1] && a[i]){
      for (j = i; a[j];j++){
        a[j] = a[j+1];
        size -= 1;
        }
      }
    }
  return size;
}
  #24  
Old 29-May-2008, 23:24
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Re: Deleting elements of arrays C++


hi, i got ur message i want to know if u r familiar with pointer and dynamic array (pointers will make it a lot easy and u can resize the array at any given time i may simplify the process) so this is what i have in mid create a function to take the user input
function initialise the array()
function to detect the duplicate input and then it must resize the array when arr[i+1]=arr[i] . incrment the counter
if u need more help with pointers and dynamic arrays let me know so i can post it and i am in the middle of my final week in school so if u are in a hurry let me know before what day u need it.
if u r not familiar with pointer and dynamic array i will suggest that u leave that alone for now till u learn about them in school and if u r not in school study those first cuz dynamic array is what making the process of resizing array possible during run time.
  #25  
Old 30-May-2008, 07:05
VulturEMaN VulturEMaN is offline
New Member
 
Join Date: May 2008
Posts: 6
VulturEMaN is on a distinguished road

Re: Deleting elements of arrays C++


Nope I'm not familiar with pointer and dynamic arrays and we don't cover that for another few weeks
  #26  
Old 30-May-2008, 08:27
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Deleting elements of arrays C++


Quote:
Originally Posted by zatora
i want to know if u r familiar with pointer and dynamic array (pointers will make it a lot easy and u can resize the array at any given time i may simplify the process)...
Okay, I have the feeling that you are repeating something I said initially in a different thread which I later tried to correct.

Let me attempt to correct your misperception again as I may not have been clear enough.

Using the following as an example:
CPP / C++ / C Code:
int f();

int main() {
    f();
    return 0;
}

int f() {
    int a[8];
    float b;

    a[7] = 2;
}
Think of what a compiler knows at the time of compilation. When compiled, the compiler will allocate sufficient space on the stack for eight integers. The next thing the compiler will do is allocate space on the stack for a float. If as a programmer, you attempt to incorrectly access a[10] instead:
CPP / C++ / C Code:
int f();

int main() {
    f();
    return 0;
}

int f() {
    int a[8];
    float b;

    a[10] = 2;
}
This code is still legal syntactically, but execution will be unpredictable because only space for eight integers has been allocated. Since access to any element within the array is treated as a pointer arithmetic problem (take the base address of the array & add the offset requested...), writing the value 2 into a[10] will result either in the value of b being corrupted or the return address back to main() being corrupted. The reason there are two potential errors here is due to hardware differences. Either the stack grows up in memory or down. Whichever direction it grows will result in a different error. Either data is corrupted or program execution may crash.

If the same array is allocated dynamically on the heap:
CPP / C++ / C Code:
int f();

int main() {
    f();
    return 0;
}

int f() {
    int *a = new int[8];
    float b;

    a[10] = 2;
}
Again, think of what is happening at compile-time. Here, space for eight integers is being allocated from the heap, but writing to a[10] is still outside of the heapspace allocated to the array. The error this will create will be different from that in the previous example, but it is still an error. Writing to a[10] is still outside the allocated heapspace. The fact that the array is allocated from the heap at run-time does not matter given that execution is controlled by instructions generated at compile-time.

The difference between declaring variables on the stack & the heap are:
  • Stack allocations are guaranteed to be contiguous -- one immediately after the other. Allocating anything from the heap may or may not be contiguous for a variety of reasons. Hence, the errors seen from malformed heap manipulations are just different from their stack counterparts.
  • Likewise, the other difference between declaring variables on the stack & allocating from the heap is that stack allocations are done at compile-time. Because allocations from the heap are deferred to run-time, how much is allocated from the heap can be determined programmatically, however, at the point where the heap allocation occurs, that allocation cannot be resized.
To be complete, C++ does implement the concept of resizable arrays, but this is done with at a higher level of abstraction in the Standard Template Library (STL) with what are called vectors. Given that this is advanced topic, you will not likely see it in your current class.
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
need help with passing 3 arrays into a function tommy69 C Programming Language 14 07-Apr-2004 01:22
Problem multiplying arrays hellhammer C Programming Language 9 29-Mar-2004 16:32
Arrays Chazza C++ Forum 10 23-Jan-2004 22:19
pointers and arrays jack C Programming Language 4 15-Jan-2004 13:27
arrays in c wolfgangaz C Programming Language 1 26-Oct-2003 05:52

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:32.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.