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

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

本文关键字:二维 静态 向量 C++98 标准 填充 使用      更新时间:2023-10-16

我有一个二维静态向量(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( 是计算数组大小的宏(

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

我正在与这个问题斗争一段时间,大多数"解决方案"都涉及切换到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。