Adding Elements at beginning of array

I need help!

I wanna know how to add new more elements to my existing array. I'm using the vector class but i no longer want to add elements at the end of the array. Can anyone help?

you can get the code here: https://onlinegdb.com/rkDCbgzDM

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//highArray.cpp
//demonstrates array class with high-level interface
#include <iostream>
#include <vector>
using namespace std;
////////////////////////////////////////////////////////////////
class HighArray
{
private:
vector<double> v; //vector v
int nElems; //number of data items
public:
//--------------------------------------------------------------
HighArray() : nElems(0) //default constructor
{ }
//--------------------------------------------------------------
HighArray(int max) : nElems(0) //1-arg constructor
{ v.resize(max); } //size the vector
//--------------------------------------------------------------
bool find(double searchKey) //find specified value
{
int j;
for(j=0; j<nElems; j++) //for each element,
if(v[j] == searchKey) //found item?
break; //exit loop before end
if(j == nElems) //gone to end?
return false; //yes, can’t find it
else
return true; //no, found it
} //end find()
//--------------------------------------------------------------
void insert(double value) //put element into array
{
v[nElems] = value; //insert it
nElems++; //increment size
}
//--------------------------------------------------------------
void insertatbegining(double value) //put element into array
{
    
   //inserting at beginning of array
    
}
//--------------------------------------------------------------
bool remove(double value) //remove element from array
{
int j;
for(j=0; j<nElems; j++) //look for it
if( value == v[j] )
break;
if(j==nElems) //can’t find it
return false;
else //found it
{
for(int k=j; k<nElems; k++) //move higher ones down
v[k] = v[k+1];
nElems--; //decrement size
return true;
}
} //end delete()
//--------------------------------------------------------------
void display() //displays array contents
{
for(int j=0; j<nElems; j++) //for each element,
cout << v[j] << " " ; //display it
cout << endl;
}
//--------------------------------------------------------------
void showmenu()
{
    cout<<"Please choose one of the options listed below: \n"
        <<"1. Insert new\n"
        <<"2. Find \n"
        <<"3. Delete \n"
        <<"4. Insert from beginning \n"
        <<"5. Show all results. \n";
        
}
//--------------------------------------------------------------
}; //end class HighArray
////////////////////////////////////////////////////////////////
int main()
{
int maxSize = 100; //array size
int number, i, item, grade;
int choice;
bool caution;
char answer;
cout<<"Welcome to your personal gradebook \n"
    <<"To begin... \n";

HighArray arr(maxSize); //vector

 arr.showmenu();
 cin>>choice;
     while (choice != 6)
     {
        switch (choice)
          {
              case 1: //insert items
                      cout<<"How much grades will you be entering? \n";
                      cin>>i;
                      for (int j=0; j<i; j++)
                      {
                      cout<<"Please enter the numbers below one by one, each one followed by pressing enter key \n";
                      cin>>number;
                      arr.insert(number);
                        }
                      arr.showmenu();
                      cin>>choice;
             break;
            
             case 2: //Find item
                     cout<<"Please enter a grade to locate \n";
                     cin>>item;
                     if (arr.find(item) )
                          {
                              cout<<"Found "<<item<<". \n";
                          }
                     else
                          {
                             cout<<"Can't locate "<<item<<"! \n";
                          };
                       arr.showmenu();
                       cin>>choice;
             break;
              
             case 3: //Delete Item
                     cout<<"Please enter the grade you would like to delete \n";
                     cin>>grade;
                     cout<<"Are you sure you would like to delete grade "<<grade<<"?! \n Enter y to continue \n";
                     cin>>answer;
                     if (answer == 'Y' or answer == 'y')
                      {
                           arr.remove(grade);
                           caution = true;
                           cout<<"Deletion successful = "<<caution<<". \n";
                      }
                     else
                     {
                           caution = false;
                           cout<<"Deletion successful = "<<caution<<". \n"
                               <<"Processed cancelled by user. \n";
                          
                      };
                     arr.showmenu();
                     cin>>choice;
             break;
             
             case 4: //Inserting Item from beginning
                     cout<<"How much grades will you be entering? \n";
                      cin>>i;
                      for (int j=0; j<i; j++)
                      {
                      cout<<"Please enter the numbers below one by one, each one followed by pressing enter key \n";
                      cin>>number;
                      arr.insertatbegining(number);
                        }
                      arr.showmenu();
                      cin>>choice;
             break;
             
             case 5: //Displaying Items
                     arr.display();
                     cout<<"--------------------------------------------------- \n";
                     arr.showmenu();
                     cin>>choice;
             break;
              
            default: cout<<"This is not an option!! \n";
          };
     };
     
     
     cout<<"Good bye \n";
//arr.display(); //display items again
return 0;
} //end main()

















Last edited on
You can use vector::insert, using begin() as the position, but that's very inefficient. You may want to consider std::list or std::deque instead.

http://en.cppreference.com/w/cpp/container/vector/insert
what, exactly, do you want to accomplish here?
you can load a vector backwards such that push back is "logically" push-front. This may make the coding a little odd (may have to iterate backwards, etc) but it is plenty efficient.

To some extent, you can preallocate the vector and jump in the middle, adding to either end as needed and once in a very infrequent while have a do-over function that copies what you have out to the middle of an even bigger vector (small performance hit).
eg: vector<int> a(1000000);
...
a[500000] = firstinsert;
a[499999] = insertedinfront;
a[500001] = insertedatback;
... etc tracking the indices yourself. Not the best plan, but doable if you are careful.

or you can do something cheesy and have a pre-items buffer that you prepend during processing to your normal buffer...

or as said map/list/etc ... some sort of priority queue could do something like this... just depends on what you need. From what I see, it looks like a map might be the thing, are you needing anything besides store and fetch?
Last edited on
What I'm trying to do is adding new elements at the beginning of the existing array. I've read alot of vector functions but simply I'm unable to determine the right function already found for the vector class.

I re-adjusted the code so that anyone can clearly see the function I'm trying to accomplish

at function:
1
2
3
4
5
6
7

void insertatbegining(double value) //put element into array
{
    
   //inserting at beginning of array
    
}


is where it needs to be specified for the program to insert new elements at beginning of the array.
Listen to kbw, who has given you sane and useful advice.
Use a container that has an efficient push_front() eg. std::deque

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <deque>

int main()
{
    std::deque<int> seq { 4, 5, 6, 7, 8 } ;

    seq.push_front(3) ; // insert 3 at the front of the sequence
    seq.push_back(9) ; // insert 9 at the back of the sequence

    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}


If for some reason, a vector must be used:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> seq { 4, 5, 6, 7, 8 } ;

    seq.insert( seq.begin(), 3) ; // add 3 to the front of the sequence
    seq.push_back(9) ; // add 9 to the back of the sequence

    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}
Yeah I did!, thank you very much kbw, and JLBorges for pointing that out.

I still have one problem tho, if I add the new element, it replaces the existing one, which that's not the idea of the function itself. The idea is to move down the other elements to create a space for the new element that will be inserted at the beginning of the array.

Here's what i have so far...

1
2
3
4
5
6
7
8
9
10
void insertatbegining(double value) //put element into array
{
    //moving existing elements down before adding new element to array.
    
    auto it = v.begin();
   //inserting at beginning of array
   it = v.insert( it, value );
   nElems++;
   
}


Am not sure if i have that right, or if i should expand the array a little more and move elements down, or whatnot. The info shared was useful btw. Just need someone to look at the code in general, help me figure out how to still keep the existing elements of the array and still add more at the beginning.
Last edited on
This is what happens when we insert items at the front:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> seq { 44, 55, 66, 78, 88 } ;

    for( int i = 10 ; i < 15 ; ++i )
    {
        seq.insert( seq.begin(), i ) ; // insert i at the front

        // print the sequence after i was inserted at the front
        std::cout << "after inserting " << i << " at the front: [ " ;
        for( int v : seq ) std::cout << v << ' ' ;
        std::cout << "] size==" << seq.size() << '\n' ;
    }
}

after inserting 10 at the front: [ 10 44 55 66 78 88 ] size==6
after inserting 11 at the front: [ 11 10 44 55 66 78 88 ] size==7
after inserting 12 at the front: [ 12 11 10 44 55 66 78 88 ] size==8
after inserting 13 at the front: [ 13 12 11 10 44 55 66 78 88 ] size==9
after inserting 14 at the front: [ 14 13 12 11 10 44 55 66 78 88 ] size==10

http://coliru.stacked-crooked.com/a/d48a0f91f316bf92
Last edited on
if you must use a vector and your requirement is to add only to the 'front' use push-back and iterate in reverse (making the 'back' of the vector the 'front' of your data) is significantly more efficient for large amounts of data. For small problems it is OK to insert.

//demonstrates array class with high-level interface

Apart from find(), display(), and showmenu() the "array class" does not add anything to the interface of std::vector.

What is the real goal? to showcase a thin wrapper of interface, or to do everything yourself -- for learning purposes?

If the first:
Why does the implementation use nElems? Why it does not use vector::size()?

Why doesn't the HighArray::find() use std::find() as implementation?
Topic archived. No new replies allowed.