从向量返回指向数组的指针

时间:2015-07-05 20:48:41

标签: c++ arrays pointers vector

存在问题:"实现一个函数来接收表示整数的正方形数组的向量向量 并返回指向包含上对角元素的副本(逐行)的1-D运行时数组的指针。" 以下是我到目前为止所做的事情,请原谅我第一次在这里发布的任何错误:

#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
const int N = 4;
int * pointer(vector<vector<int>>amatrix)
{
    int L = (N*N - N) / 2;
    int * b;
    b = new int[L];
        for (int i = 0; i < N-1; i++)
            for (int j = 1; j < N; j++)
            {
                int c = amatrix[i][j];
                for (int k = 0; k < (N*N - N) / 2; k++)
                    b[k] = c;
            }
    return b;
}
void main()
{
    vector<vector<int>>amatrix(N, vector<int>(N));
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            amatrix[i][j] = rand() % 10;
            cout << amatrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    for (int i = 0; i < (N*N - N) / 2; i++)
        cout << pointer(amatrix)[i] << " ";

    cout << endl;
    system("pause");
} 

1 个答案:

答案 0 :(得分:0)

捕捉! :)

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

int * pointer( const std::vector<std::vector<int>> &amatrix )
{
    size_t n = amatrix.size();
    size_t size = ( n * n - n ) / 2;

    int *p = new int[size];
    int *q = p;

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = i + 1; j < n; j++ ) *q++ = amatrix[i][j];
    }        

    return p;
}

int main()
{
    const size_t N = 4;

    std::vector<std::vector<int>> amatrix( N, std::vector<int>( N ) );

    std::srand( ( unsigned int )std::time( 0 ) );

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) amatrix[i][j] = std::rand() % 10;
    }

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) std::cout << amatrix[i][j] << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;

    int *p = pointer( amatrix );

    for ( size_t i = 0; i < ( N * N - N ) / 2; i++ ) std::cout << p[i] << ' ';
    std::cout << std::endl;

    delete []p;
}

程序输出可能看起来像

6 3 4 7 
6 0 1 2 
9 9 7 8 
8 8 4 4 

3 4 7 1 2 8 

至于你的代码,然后在函数

中循环
            for (int k = 0; k < (N*N - N) / 2; k++)
                b[k] = c;

没有意义。

同样没有意义为循环的每次迭代调用函数

for (int i = 0; i < (N*N - N) / 2; i++)
    cout << pointer(amatrix)[i] << " ";

因为会有内存泄漏,因为每次调用它时都会分配一个新数组。