0

How to insert an element at specific position in an array of integer like int a[10]; i want to insert an element at position 2.

#before insertion a={1,2,4,5,6,7,8,9,0,0}; #after insertion a={1,2,3,4,5,6,7,8,9,0};

24th Feb 2017, 3:48 PM
Deepak Sharma
Deepak Sharma - avatar
2 Respostas
+ 2
I don't know a whole lot about Java, so this answer will be specifically about C++. For basic arrays, there's no built-in positional insertion like you're describing. You'll either have to write the function yourself, or use a std::vector. In the first case, it would look something like this: void insert(int* arr, int size, int pos, int val) { //Walk backwards over the array from one before the end // to insertion position, copying elements right one //The final element gets overwritten, as in your example. for(int i = size - 2; i >= pos; --i){ arr[i + 1] = arr[i]; } //Put the value at the insertion point arr[pos] = val; } //Then in main... int main(){ int size = 10; int arr[size] = {1,2,4,5,6,7,8,9,0,0}; //Insert into array of given size at position 2 the value 3. insert(arr, size, 2, 3); return 0; } A std::vector is basically an array that can resize itself as needed, and it has a build-in insert method. This makes insertion a lot easier, and the vector will automatically resize itself on insertion. Note that you have to #include <vector> to use this. #include <vector> int main(){ //This just says "Make a vector that can hold ints called v." std::vector<int> v = {1,2,4,5,6,7,8,9,0,0}; //Then you use v.insert(where, what) v.insert(2, 3); //v is now {1,2,3,4,5,6,7,8,9,0,0} - 3 was inserted, and the vector got longer return 0; } Hope this helped!
24th Feb 2017, 6:13 PM
Matthew
0
a[index] = value; In your case will be: a[2] = 3;
24th Feb 2017, 4:11 PM
Marcellino Chris O'vara
Marcellino Chris O'vara - avatar