使用 C++98 标准填充二维静态向量

Populating a two dimension static vector using C++98 standard

我有一个需要填充的二维静态向量 (std::vector< std::vector<double> >),我正在处理一个需要使用 C++98 编译的旧项目。因此,我不允许使用 std::vector<...> v = { {1,2}, {3,4} }; 语法。

对于一维向量,将数组分配为 double a[] = {1,2}; 然后使用 std::vector<double> v(a, a+2) 就可以了;但是,它不适用于二维向量。

std::vector< std::vector<double> >
x1_step_lw_2(__x1_step_lw_2,
             __x1_step_lw_2 + ARRAY_SIZE(__x1_step_lw_2));

我收到以下错误:

../src/energyConsumption/ue-eennlite-model-param-7IN-30NN.cpp:193:33:   required from here                                                   
/usr/include/c++/4.8/bits/stl_construct.h:83:7: error: invalid conversion from ‘const double*’ to ‘std::vector<double>::size_type {aka long \
unsigned int}’ [-fpermissive]                                                                                                                
       ::new(static_cast<void*>(__p)) _T1(__value); 

(ARRAY_SIZE(x)是一个计算数组大小的宏)

并且由于这些向量是 class 的属性,因此在构造函数上启动它们没有任何意义。

我与这个问题斗争了一段时间,大多数 'solutions' 涉及切换到 C++11,这不是一个选项。

感谢任何帮助。

我的 C++98 生锈了,但像这样的东西应该可以工作:

double a[] = { 1, 2 };
double b[] = { 3, 4 };
double c[] = { 5, 6 };

std::vector<double> v[] =
{
    std::vector<double>(a, a + ARRAY_SIZE(a)),
    std::vector<double>(b, b + ARRAY_SIZE(b)),
    std::vector<double>(c, c + ARRAY_SIZE(c))
};

std::vector< std::vector<double> > vv(v, v + ARRAY_SIZE(v));

试试这个:

#include <iostream>
#include <vector>

/**this generates a vector of T type of initial size N, of course it is upto you whether you want to use N or not, and returns the vector*/
template<class T>
std::vector<T> generateInitVecs(size_t N)
{
    std::vector<T> returnable;

    for(int i = 0; i < N; i++)
        returnable.push_back(0);

    return returnable;
}

int main()
{
    std::vector< std::vector<double> > twoDvector;
    /**Since twoDvector stores double type vectors it will be first populated by double type vectors*/
    for(int i = 0; i < 10; i++){
        twoDvector.push_back(generateInitVecs<double>(10));
    }

    /**populating the vector of vectors*/
    for(int i = 0; i < 10; i++)
        for(int j = 0; j < 10; j++){
            /**can be treated as 2D array*/
            twoDvector[i][j] = 50;
        }

    for(int i = 0; i < 10; i++){
        for(int j = 0; j < 10; j++){
            std::cout << twoDvector[i][j] << " ";
        }
        std::cout << "\n";
    }
}

它将打印一个 10 x 10 矩阵,所有值都指定为 50。