Hi,
I tried to present a 2D mathematic matrix with C++ vector and expand it by repeating the first and last row and column. An example for intuition, I initialized a 2D C++ vector vec_2d to be as following:
1, 2, 3, 4
5, 6, 7, 8
9,10,11,12
13,14,15,16,
and I want to expand it to be:
1, 1, 2, 3, 4, 4
1, 1, 2, 3, 4, 4
5, 5, 6, 7, 8, 8
9, 9,10,11,12,12
13,13,14,15,16,16
13,13,14,15,16,16
by first repeat the first and last rows and then the updated first and last columns.

The code is as following:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<short>vec;
	vector< vector<short> >vec_2d;
	vector< vector<short> >vec_2d_padded;
	// Initialize a 2D C++ vector.
	for (int i=1; i<17; i++)
	{
		vec.push_back(i);
		if (i%4 == 0)
		{
			vec_2d.push_back(vec);
			vec.clear();
		}
	}
	// Expand by repeating the first and last row.

	vector< vector<short> >::iterator it;
	it = vec_2d.begin();
	vec_2d.insert(it,vec_2d.front());
	vec_2d.push_back(vec_2d.back());

	vector<short>::iterator it_1d;

	// Things seem to go bad here.
	for (it=vec_2d.begin(); it<vec_2d.end(); it++)
	{
		for (it_1d=(*it).begin(); it_1d=(*it).end(); it_1d++)
		{
			cout<<" "<<*it_1d;
		}
	}
	return 0;
}

I have written the code to expand the vector by repeating the first and last rows but I do not know how to repeat the first and last columns. Another problem is, I do not know how to check if I am right by printing all the elements in the vector, the code I have written for this purpose seems to work badly. Anyone can tell me why and help me out? Thank you in advance.

nanchuangyeyu

You had an assignment in your inner loop condition rather than a comparison. I also added the code to insert the new columns as it's an identical operation to inserting the new rows:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<short>vec;
    vector< vector<short> >vec_2d;
    vector< vector<short> >vec_2d_padded;
    // Initialize a 2D C++ vector.
    for (int i=1; i<17; i++)
    {
        vec.push_back(i);
        if (i%4 == 0)
        {
            vec_2d.push_back(vec);
            vec.clear();
        }
    }

    // Expand by repeating the first and last row.
    vector< vector<short> >::iterator it;
    it = vec_2d.begin();
    vec_2d.insert(it,vec_2d.front());
    vec_2d.push_back(vec_2d.back());

    // Things seem to go bad here.
    for (it=vec_2d.begin(); it<vec_2d.end(); it++)
    {
        vector<short>::iterator it_1d;

        // Expand by repeating the first and last column
        it->insert ( it->begin(), it->front() );
        it->push_back ( it->back() );

        for (it_1d=(*it).begin(); it_1d != (*it).end(); it_1d++)
        {
            cout<<" "<<*it_1d;
        }

        cout<<'\n';
    }
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.