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

Dani AI

Generated

Short note: correctly spotted the printing bug (you used assignment = in the loop condition) and showed an in-place insert approach to duplicate edge columns. That works, but modifying containers while iterating can be fragile. A clearer, safer pattern is to build a new padded matrix and copy elements with "edge clamping" — map every padded coordinate back to the nearest source coordinate (0..n-1). This avoids iterator invalidation, naturally handles rectangular matrices, and is easy to reason about.

Example function (generic, returns a new padded matrix):

template<typename T>
std::vector<std::vector<T>> pad_with_edge(const std::vector<std::vector<T>>& src) {
    if (src.empty() || src[0].empty()) return src;
    size_t rows = src.size(), cols = src[0].size();
    for (size_t i = 1; i < rows; ++i)
        if (src[i].size() != cols) throw std::invalid_argument("Non-rectangular input");

    std::vector<std::vector<T>> dst(rows + 2, std::vector<T>(cols + 2));
    for (size_t r = 0; r < rows + 2; ++r) {
        for (size_t c = 0; c < cols + 2; ++c) {
            size_t sr = (r == 0) ? 0 : (r == rows + 1 ? rows - 1 : r - 1);
            size_t sc = (c == 0) ? 0 : (c == cols + 1 ? cols - 1 : c - 1);
            dst[r][c] = src[sr][sc];
        }
    }
    return dst;
}

Use it, then print with simple index loops (avoid = vs != mistakes). Complexity: O(R*C) time and space. Notes and troubleshooting: check for empty or ragged inputs; use the rectangle check above or handle rows of different lengths explicitly. If you prefer in-place expansion, iterate an outer copy or insert rows/cols carefully (inserting into the outer vector while iterating will invalidate iterators). Finally, prefer explicit index arithmetic for the clamping logic to avoid size_t underflow (don’t do i-1 when i might be unsigned zero without a guard).

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.