Newbie - Split an array in two and return

Hello all - I'm VERY new to C++ so please forgive me. I've been given the following tasks and I'm just lost. "Unsorted Type" is an ADT that is to be extended and is a class UnsortedType.

I have to create a function that will return 2 arrays from one that is given. It should split the array based on an initial "item" given and the elements of the array should be assigned to list1 if <= item otherwise assigned to list2.

It is really returning the 2 lists that I'm stumped because I'm given the following:

function SplitLists(UnsortedType list, ItemType item, UnsortedType& list1, UnsortedType& list2)

I have to do this two ways. The first was "a" has to be done by array based member function of Unsorted List ADT. The second way "b" is to be done as a linked member function

Thanks for help,
Ed
It's not so bad. The two lists are passed in, you just need to copy each elements from list onto list1 or list2 depending if it's less than or equal to item.

You can start by writing the function and writing the loop that traverses list. Then in the loop, check if the entry is less than or equal to item.

Once you've done that, you just append that value onto either list1 or list2.
If you are allowed to use C++ algorithm, you can use the partition function to partition into 2 ranges and then the copy function to copy the first range and second range into 2 respective destinations (in your case 2 destination arrays).

http://www.cplusplus.com/reference/algorithm/partition/

http://www.cplusplus.com/reference/algorithm/copy/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

class isBigger {
  public:
  int initItem;
  isBigger(int i) { initItem = i; }
  bool operator()(int ii) {
    return ii<initItem;
  }
};

int main() {
  vector<int> a;
  a.push_back(10);
  a.push_back(12);
  a.push_back(6);
  a.push_back(5);
  a.push_back(1);
  a.push_back(100);

  int initialItem = 7;
  vector<int>::iterator bound = partition(a.begin(),a.end(),isBigger(initialItem));

  vector<int> firstVec;
  vector<int> secondVec;

  copy (a.begin(), bound, back_inserter(firstVec));
  copy (bound, a.end(), back_inserter(secondVec));

  cout << "first vec ...\n";
  copy(firstVec.begin(), firstVec.end(), ostream_iterator<int>(cout,"\n"));
  cout << "second vec ...\n";
  copy(secondVec.begin(), secondVec.end(), ostream_iterator<int>(cout,"\n"));

  return 0;
}
sohguanh It's better not to do other people's homework.
Topic archived. No new replies allowed.