Move All Columns Of A Matrix To The Left By One C++ - c++

my problem is to take a matrix mat of rowcol length, and move each column within it one position to the left.
For example if i have a 3x3 matrix like this:
4 5 2
6 7 3
3 4 6
the result should must be like this:
5 2 4
7 3 6
4 6 3
I can't get the method to work, how many times I do it, does anyone have any ideas?
Below my code:
for(int i = rowcol - 1; i > 0; i--)
for(int j = 0; j < rowcol; j++) {
if(i == 0) swap(mat[j][rowcol - 1], mat[j][i]);
swap(mat[j][i], mat[j][i-1]);
}

The standard library has an algorithm to do what you're asking: std::rotate. The following example rotates everything right one column.
#include <iostream>
#include <algorithm>
int main()
{
int arr[][3] = {
{ 1,2,3 },
{ 4,5,6 },
{ 7,8,9 }
};
for (auto& row : arr)
{
std::rotate(row, row+2, row+3);
}
for (auto& row : arr)
{
for (auto x : row)
std::cout << x << ' ';
std::cout << '\n';
}
}
Output
3 1 2
6 4 5
9 7 8
Obviously the conditions of your matrix access to individual rows can be (and is likely) different than the above trivial example, but nonetheless, the concept is still the same. I leave it to you to play with for learning how to do it "left" (it won't be hard *).
hint: std::rotate(row, row+1, row+3);

Here's my updated solution. It's even easier than the original one I posted a few minutes earlier.
Basically, for each row:
Save off the value in the first column
Shift all the values (starting at column 1) in the row by one to the left.
The last value in the row is the previously saved variable from the first step
Code:
for (size_t row = 0; row < rowcol; row++) {
int tmp = mat[row][0];
for (size_t col = 1; col < rowcol; col++) {
mat[row][col-1] = mat[row][col];
}
mat[row][rowcol-1] = tmp;
}

What about as follows ?
for ( auto ui = 0u ; ui < rowcol ; ++ui )
for ( auto uj = 1u ; uj < rowcol ; ++uj )
std::swap(mat[ui][uj-1], mat[ui][uj]);
The following is a full compiling example
#include <iostream>
static constexpr std::size_t rowcol = 3u;
void printMat (int mat[rowcol][rowcol])
{
for ( auto ui = 0u ; ui < rowcol ; ++ui ) {
for ( auto uj = 0u ; uj < rowcol ; ++uj )
std::cout << mat[ui][uj] << ' ';
std::cout << std::endl;
}
std::cout << std::endl;
}
int main()
{
int mat[rowcol][rowcol] { {4, 5, 2}, {6, 7, 3}, {3, 4, 6} };
printMat(mat);
for ( auto ui = 0u ; ui < rowcol ; ++ui )
for ( auto uj = 1u ; uj < rowcol ; ++uj )
std::swap(mat[ui][uj-1], mat[ui][uj]);
printMat(mat);
}

Your logic is correct except, you're actually shifting the columns of the matrix one position to the right, not left. Not only that, the (i==0) condition is not required.
Replace the backward iteration with forward iteration and get rid of the conditional statement and you're good to go. Here's the modified code:
for(int i = 0; i < rowcol-1; i++)
for(int j = 0; j < rowcol; j++) {
// if(i == 0) swap(mat[j][rowcol - 1], mat[j][i]);
swap(mat[j][i], mat[j][i+1]);
}
Basically your logic is similar to Bubble Sort. You were bubbling the final column towards the beginning of the matrix by shifting all other columns rightward.
I inverted it by making it so that we are bubbling the first column towards the end instead. Feel free to ask any questions.

Related

Rotating matrix by 90 degress in anticlockwise direction , where am i going wrong

Given a square matrix mat[ ][ ] of size N x N. The task is to rotate it by 90 degrees in anti-clockwise direction without using any extra space. Problem Link
My Logic - for a matrix N x N, rotate the outer window in an anticlockwise direction by swapping elements starting from left column -> bottom row -> right column -> top row using temp variable X-1 time where X is the dimension of the outer window. I don't know why it's not working. Please Help me spot the problem.
#include<bits/stdc++.h>
using namespace std;
int main() {
int t=1; cin>>t;
while (t--) {
int n; cin>>n; vector<vector<int>>a(n,vector<int>(n));
for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>a[i][j];
for(int k=0;k<n;k++) {
int i=k, j=0, p=n-1-k, q=p-i, temp;
while (q-- && i<p) {
temp=a[i][i];j=i;
while (j<=p) {
swap(temp, a[j][i]);j++;
}j=i+1;
while (j<=p) {
swap(temp, a[p][j]);j++;
}j=p-1;
while (j>=i) {
swap(temp, a[j][p]); j--;
}j=p-1;
while (j>=i) {
swap(temp, a[i][j]); j--;
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) cout<<a[i][j]<<" ";
cout<<"\n";
}
cout<<"\n";
}
}
Thank You
I would like to suggest an approach that looks more simpler.
Let's assume that you have a vector of vectors of the type char like this.
a b c d
e f g h
i j k l
m n o p
The result vector must look like
d h l p
c g k o
b f j n
a e i m
The result vector can be built in two steps.
In the first step the rows of the source vector are swapped.
m n o p
i j k l
e f g h
a b c d
In the second step there are swapped elements relative to the side diagonal that is for example 'm' is swapped with 'd', 'n' is swapped with 'h' and 'o' is swapped with 'l'. Then these operations are repeated for element of the second row the second column from the end of the vector.
Here is a demonstrative program.
#include <iostream>
#include <utility>
#include <vector>
int main()
{
std::vector<std::vector<char>> a =
{
{ 'a', 'b', 'c', 'd' },
{ 'e', 'f', 'g', 'h' },
{ 'i', 'j', 'k', 'l' },
{ 'm', 'n', 'o', 'p' },
};
auto n = a.size();
for ( const auto &row : a )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
for ( size_t i = 0; i < n / 2; i++ )
{
std::swap( a[i], a[n-i-1] );
}
for ( const auto &row : a )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
for ( size_t i = 0; i + 1 < n; i++ )
{
for ( size_t j = 0; j + i + 1 < n; j++ )
{
std::swap( a[i][j], a[n-j -1][n - i -1]);
}
}
for ( const auto &row : a )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
The program output is
a b c d
e f g h
i j k l
m n o p
m n o p
i j k l
e f g h
a b c d
d h l p
c g k o
b f j n
a e i m
[Note: my previous solution uses extra memory, this one doesn't. So, I've deleted the previous solution and totally updated it to provide the new one].
Well, this problem can be solved easily if we are able to use extra space, but that is not the case. Anyway, it can also be solved easily without using another extra space.
At first, let me explain my solution for this problem. Then, I'll tell you about the wrong doing in your code. My solution is similar to your approach. It considers the input array as layers of rings or loops. See below:
0 0 0 0 0
0 1 1 1 0
0 1 2 1 0
0 1 1 1 0
0 0 0 0 0
The outer ring is the 0's, the inner ring is the 1's and so on...
Now, for arguments sake, let's assume we're using extra space b(we won't use this space in solution though). Also, let us assume, b is the solved array that contains the rotated matrix. Then, we may say:
b[(n + n - j - 1) % n][i] = a[i][j] // for any i, j
// here "n" is dimension of matrix
// "i", represents ith indexed row of a
// "j", represents jth indexed column of a
// if you having problem, how this thing just dropped from sky, then
// just write down in paper, for some index (x, y) what it becomes when it is rotated
// you'll see some formula like I've described above
Okay, now, if you're clear with the formula, let me describe how this helps to solve problem:
In the previous ring figure(the one I've used for showing rings), you can see that the corner elements of the 0's rings just changed with each other, i.e. the corner elements just swap places with each other when the matrix rotated, they never interfere with other elements. This is also, true for other elements too. There is always four elements in a group, and they just swap position with each other! There's only one exception is the center(if n is odd). And the center never changes position...
If you've also, observed the loop/group of four elements, those just swap position with each other, then we can just find out the next element's position from present element's position and place the present element's value and we're done... So, how do find out next position's value. Notice, we've already talked about it, how b's result is calculated from a. So, we may write something below:
pair<int, int> getNext(pair<int, int> x, int n) {
return make_pair((n + n - x.second - 1) % n, x.first);
}
Now, come to rings, how many are there, that we should care about, well it's (n/2) rings. So, we'll just go to each ring, iterate through the elements of the first row of each ring(except the last one, cause it's included in the corner) and run a loop of four to replace the value properly in position. The full code is given below:
#include <iostream>
#include <string>
#define N 128
// returns next postition based on present position
// next position means where the present position value should
// be transferred after rotation
pair<int, int> getNext(pair<int, int> x, int n) {
return make_pair((n + n - x.second - 1) % n, x.first);
}
int main() {
int a[N][N];
int n;
scanf("%d", &n);
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &a[i][j]);
}
}
for(int h = 0; h < (n / 2); h++) {
int s = h;
int e = n - h - 1;
for(int k = s; k < e; k++) {
auto p = make_pair(s, k); // row = s, and col = k
int t = a[p.first][p.second];
for(int c=0; c<4; c++) {
auto p2 = getNext(p, n);
int temp = a[p2.first][p2.second];
a[p2.first][p2.second] = t;
t = temp;
p = p2;
}
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Now, what is wrong with your code:
I guess, you've already understood, that your algo is not correct...and the implementation is buggy too...
[P.S.]: pls, don't just copy paste the code, first understand it. Also, write code in a manner, so other's can read...and if any error you find with the algo I've provided or you may have problem with understanding any concept, let me know in the comment...

Shifting Objects Up in an Array

I'm creating a program that creates an array of objects in random positions in an array size 8. Once created, I need them to sort so that all the objects in the array are shifted up to the top, so no gaps exist between them. I'm almost there, but I cannot seem to get them to swap to index 0 in the array, and they instead swap to index 1. Any suggestions? (Must be done the way I'm doing it, not with other sorting algorithms or whatnot)
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct WordCount {
string name = "";
int count = 0;
};
int main() {
cout << "Original random array: " << endl;
srand(static_cast<int>(time(0)));
int i = 0;
WordCount wordArr[8];
while (i < 4) {
int randomNum = 0 + (rand() % static_cast<int>(7 + 1));
if(wordArr[randomNum].name == "") {
wordArr[randomNum].name = "word" + static_cast<char>(i);
wordArr[randomNum].count = i;
i++;
}
}
int j = 0;
while (j < 8) {
cout << wordArr[j].name << " " << wordArr[j].count << endl;
j++;
}
cout << "\n\nSorted array: " << endl;
for (int i = 7; i >= 0; i--) {
for (int j = 0; j <= 7; j++) {
if (wordArr[i].name != "") {
if (wordArr[j].name == "") {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
}
int k = 0;
while (k < 8) {
cout << wordArr[k].name << " " << wordArr[k].count << endl;
k++;
}
return 0;
}
If I understand your requirement correctly, you want to move all the non-blank entries to the start of the array. To do this, you need an algorithm like this for example:
for i = 0 to 7
if wordArr[i].name is blank
for j = i + 1 to 7
if wordArr[j].name is not blank
swap [i] and [j]
break
So, starting from the beginning, if we encounter a blank entry, we look forward for the next non-blank entry. If we find such an entry, we swap the blank and non-blank entry, then break to loop again looking for the next blank entry.
Note, this isn't the most efficient of solutions, but it will get you started.
Note also I'd replace the 4 and 8 with definitions like:
#define MAX_ENTRIES (8)
#define TO_GENERATE_ENTRIES (4)
Finally:
wordArr[randomNum].name = "word" + static_cast<char>(i);
That will not do what you want it to do; try:
wordArr[randomNum].name = "word" + static_cast<char>('0' + i);
To append the digits, not the byte codes, to the end of the number. Or perhaps, if you have C++11:
wordArr[randomNum].name = "word" + std::to_string(i);
I see couple of problems.
The expression "word" + static_cast<char>(i); doesn't do what you are hoping to do.
It is equivalent to:
char const* w = "word";
char const* p = w + i;
When i is 2, p will be "rd". You need to use std::string("word") + std::to_string(i).
The logic for moving objects with the non-empty names to objects with empty names did not make sense to me. It obviously does not work for you. The following updated version works for me:
for (int i = 0; i <= 7; ++i) {
// If the name of the object at wordArr[i] is not empty, move on to the
// next item in the array. If it is empty, copy the next object that
// has a non-empty name.
if ( wordArr[i].name == "") {
// Start comparing from the object at wordArr[i+1]. There
// is no need to start at wordArr[i]. We know that it is empty.
for (int j = i+1; j <= 7; ++j) {
if (wordArr[j].name != "") {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
}
There was two problems as :
wordArr[randomNum].name = "word" + static_cast<char>(i); this is not what your are looking for, if you want that your names generate correctly you need something like this :
wordArr[randomNum].name = "word " + std::to_string(i);
Your sorting loop does not do what you want, it's just check for the "gaps" as you said, you need something like this :
for (int i = 0; i < 8; ++i) {
for (int j = i+1; j < 8; ++j) {
if (wordArr[i].name == "" || (wordArr[i].count < wordArr[j].count)) {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
Your algorithm sorts the array, but then looses the sorting again.
You want to swap elements only when i > j, in order to push elements to the top only. As a result, you need to change this:
if (wordArr[j].name == "")
to this:
if (wordArr[j].name == "" && i > j)
Consider this array example:
0
ord 1
0
0
rd 2
word 0
d 3
0
Your code will sort it to:
d 3
ord 1
word 0
rd 2
0
0
0
0
but when i = 3, it will try to populate the 5th cell, and it will swap it with rd 2, which is not what we want.
This will push rd 2 down, but we don't want that, we want gaps (zeroes) to go to the end of the array, thus we need to swap eleemnts only when they are going to go higher, not lower, which is equivalent to say when i > j.
PS: If you are a beginner skip that part.
You can optimize the inner loop by using one if statement and a break keyword, like this:
for (int j = 0; j <= 7; j++) {
if (wordArr[i].name != "" && wordArr[j].name == "" && i > j) {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
break;
}
}

How to fill a 2D array with Every Possible Combination? C++ Logic

I can't figure out the logic behind this one... here's what I have so far:
#include <iostream>
using namespace std;
int thearray[4][4];
int NbPos = 4;
int main() {
int i2;
int q2;
for(int i = 1; i < 4; i++) {
for(int q = 1; q < 4; q++) {
for(int c = 0; c < NbPos; c++) {
thearray[i][q] = c;
}
}
}
}
This is filling the array up to the end is still:
3 3 3
3 3 3
3 3 3
but it's doing so without hitting anywhere near every possible combination.
Ideally once it gets to:
0 0 0
0 0 0
0 0 3
the next step SHOULD be:
0 0 0
0 0 0
0 1 0
so it hits a TON of combinations. Any ideas on how to make it hit them all? I'm stumped on the logic!
with the way you're iterating over this, a 1-dimensional array would make the looping simpler. you can still mentally treat it to have rows and columns, however they are just layed out end-to-end in the code.
you could try something like this; however if you want it in a 2D format specifically that challenge is left to you ;)
#include <iostream>
using namespace std;
#define rows 4
#define columns 4
int main() {
int thearray[rows * columns] = {0};
int NbPos = 4;
int lastPos = rows * columns - 1;
while (true) {
thearray[lastPos]++;
int pos = lastPos;
while (thearray[pos] == NbPos and pos >= 1) {
thearray[pos - 1]++;
thearray[pos] = 0;
pos--;
}
bool finished = true;
for (int i = 0; i < rows * columns; i++) {
if (thearray[i] != NbPos - 1) {
finished = false;
}
}
if (finished) {
break;
}
}
for (int i = 0; i < rows * columns; i++) {
std::cout << thearray[i] << " ";
if (i % rows == rows - 1) {
cout << endl; // makes it look like a 2D array
}
}
}
It makes sense to have the final form as all 3s , since you loop every element of the array and you assign it at the end with 3 .
So the next element will only take into account the combination with the final value of the previous element (which will be 3).
Thinking in math terms, your complexity is N^3 so to speak (actually is N^2 * 4 , but since your N is 3 ...).
Your approach is wrong, since you want to find permutations, which are defined by a factorial function , not a polinomial function.
The necessary complexity for the output doesn't match the complexity of your algorithm (your algorithm is incredbily fast for the amount of output needed).
What you are looking for is backtracking (backtacking will match the complexity needed for your output).
The recursion function should be something like this (thinking on a 1D array, with 9 elements):
RecursiveGeneratePermutations(int* curArray, int curIdx)
{
if (curIDX==9)
{
for (int i=0; i<9;i++)
{
// write the array
}
} else {
curArray[curIdx]=0;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=1;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=2;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=3;
RecursiveGeneratePermutations(curIdx+1);
}
}
Now you only need to call the function for the index 0 :
RecursiveGeneratePermutations(arrayPtr,0);
Then wait...allot :).

Distinct numbers in c++

I want to start by saying I am new to programming. I have a problem with writing a list of distinct numbers from another list in c++. Let's say I have a list l1 = {1, 12, 2, 4, 1, 3, 2} and I want to create a new list that looks like this l2 = {1, 12, 2, 4, 3}...
This is what I wrote:
#include <iostream>
using namespace std;
int main() {
int l1[100], l2[100], length, length1 = 0, i, j, a = 0;
cin >> length; //set the length
for (i = 0; i < length; i++) {
cin >> l1[i]; //add numbers to the list
}
l2[0] = l1[0]; //added the first number manually
for (i = 0; i < length; i++) {
length1++;
a = 0;
for (j = 0; j < length1; j++) {
if (l1[i] != l2[j]) //this checks numbers in the second list
a = 1; // and if they aren't found a gets the value
} //1 so after it's done checking if a is 1 it
if (a == 1) //will add the number to the list, but if the
l2[j] = l1[i]; //number is found then a is 0 and nothing happens,
} // SUPPOSEDLY
for (j = 0; j < length1; j++) {
cout << l2[j] << " ";
}
}
The output of this is 1 -858993460 12 2 4 1 3 so obviously I did something very wrong. I'd welcome any suggestion you might have, I don't necessarily need a solution to this, I just want to get unstuck.
Thanks a lot for taking time to reply to this.
std::sort(l1, l1 + 100);
int* end_uniques = std::unique(l1, l1 + 100);
std::copy(l1, end_uniques, l2);
size_t num_uniques = end_uniques - l1;
This is O(N log N) instead of your O(N^2) solution, so theoretically faster. It requires first sorting the array l1 (in-place) to let std::unique work. Then you get a pointer to the end of the unique elements, which you can use to copy to l2 and of course get the count (because it may be less than the full size of 100 of course).
Most Important : This solution assumes that we've to preserve order
Well....
try out this one....
I've changed identifiers a bit ( of course that's not gonna affect the execution )
It'll just help us to identify what is the sake of that variable.
Here's the code
#include <iostream>
using namespace std;
int main()
{
int Input[100], Unique[100], InSize, UniLength = 0;
cin >> InSize;
for (int ii = 0 ; ii < InSize ; ii++ )
{
cin >> Input[ii];
}
Unique[0] = Input[0];
UniLength++;
bool IsUnique;
for ( int ii = 1 ; ii < InSize ; ii++ )
{
IsUnique=true;
for (int jj = 0 ; jj < UniLength ; jj++ )
{
if ( Input[ii] == Unique[jj] )
{
IsUnique=false;
break;
}
}
if ( IsUnique )
{
Unique[UniLength] = Input[ii];
UniLength++;
}
}
for ( int jj = 0 ; jj < UniLength ; jj++ )
{
cout << Unique[jj] << " ";
}
}
You were inserting Unique element at it's original index in new array..... and in place of those elements which were duplicate.... you was not doing any kind of shifting.... i.e. they were uninitialized..... and were giving something weird like -858993460
I appreciate above mentioned two answers but again..... I think this question was placed on hackerrank.... and unqiue_array() doesn't work there.....
Added
Of course we can only add Unique elements to our Input array..... but... this solution works..... Moreover we have 2 seconds of execution time limit.... and just 100 elements..... Keeping in mind.... that Big Oh Notation works good for really large Inputs .... Which is not case here....So there's really no point looking at time complexity....... What I'll choose is the algorithm which is easy to understand.
I hope this is what you were looking for...
Have a nice day.

Erasing an element from 2D vector c++

I have a unsymmetrical vector in 2D.
vector< vector<int> > Test
where Test =
2 4 6 5 7
6 5 7 9 10
5 9 10
9 10
I am reading the row 1 and if any element of this is present in other rows then delete it.
for eaxmple.. After reading row 1, i have to remove 6, 5, and 7 from other rows.
However, It is not working
Here is the code i am trying
Test[i].erase(Test[i].begin()+j);
where i = row and j is col.
My code is :
for (i =0; i < Test.size();i++)
{
for (j=0; j < Test[i].size();j++)
{
// removed repeated element
if (i >0)
{
Test[i].erase(Test[i].begin() +j);
}
}
}
Maybe it is nor very nice but it works
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<std::vector<int>> v =
{
{ 2, 4, 6, 5, 7 },
{ 6, 5, 7, 9, 10 },
{ 5, 9, 10 },
{ 9, 10 }
};
for ( const auto &row : v )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
std::cout << std::endl;
if ( !v.empty() )
{
for ( auto it = std::next( v.begin() ); it != v.end(); ++it )
{
auto is_present = [&]( int x )
{
return std::find_if( v.begin(), it,
[x]( const std::vector<int> &v1 )
{
return std::find( v1.begin(), v1.end(), x ) != v1.end();
} ) != it;
};
it->erase( std::remove_if( it->begin(), it->end(), is_present ),
it->end() );
}
}
for ( const auto &row : v )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The output is
2 4 6 5 7
6 5 7 9 10
5 9 10
9 10
2 4 6 5 7
9 10
You can place the values encountered in each row in a set, and then query every element in a new row for existence in that set. Such a function would look like this :
void RemoveRowDuplicates(vector<vector<int>> &v)
{
std::set<int> vals;
for(auto &vec : v)
{
vec.erase(remove_if(vec.begin(), vec.end(), [&](int k){
return vals.find(k) != vals.end();
}), vec.end());
vals.insert(vec.begin(), vec.end());
}
}
What exactly do you think is Test[i].begin()+j? Is ist a set of elements you want to erase? I don't think so. It should be just an iterator, that points to a single element, but you want to delete all elements, that are already in your datastructure.
If I understood, what you want to do, try:
for(int j = 0; j < Test.size(); j++){ //iterate over other rows
if(j == i)
continue;
for(int k = 0; k < Test[j].size(); k++){ //iterate over elements of the rows
int elementToRemove = (Test[j])[k];
vector<int>::iterator it = Test[i].begin();
while (it != Test[i].end()) { //iterate over row i
if((*it) == elementToRemove){ //erase the element if it matches the actual
it = Test[i].erase(it);
}else{
it++;
}
}
}
}
You could execute the code for every possible i. Maybe start form i = 0 to n. If I refer to your code, that you added put the code above in between your
for (i =0; i < Test.size();i++){
//my code here...
}
Edit: Used iterator now to delete. The first version was not correct.
Edit2: Changed the index of the first loop and added continue statement.
This works for me:
int i = 0;
for ( int j = i+1; j < Test.size(); ++j )
{
for ( int k = 0; k < Test[i].size(); ++k )
{
std::vector<int>::iterator iter = Test[j].begin();
std::vector<int>::iterator end = Test[j].end();
for ( ; iter != end; )
{
if ( *iter == Test[i][k] )
{
iter = Test[j].erase(iter);
}
else
{
++iter;
}
}
}
}
Consider the following 2D vector
myVector=
1 2 3 4 5 -6
6 7 8 -9
8 -1 -2 1 0
Suppose we want to delete the element myVector[row][column] for appropriate row and column indices.
Look at the following code:
void delete_element(vector<int>& temp, col)
{
temp.erase(temp.begin()+col);
}
int main()
{
//Assume that the vector 'myVector' is already present.
cin>>row>>column;
delete_element(myVector[row],column);
}
What we basically do is,we get the row and column of the element to be deleted. Now as this 2D vector is a vector of vectors, we pass the vector(the row containing the element to be deleted) and the column as parameters to a function. Note that the row-vector is passed as a reference ('&' in vector parameter).
Now the problem becomes quite as simple as deleting an element from a 1D vector.
Hope this helps!