我有一个二维静态矢量(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,这不是一个选择。
感谢您的帮助。
答案 0 :(得分:3)
我的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));
答案 1 :(得分:1)
尝试一下:
#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。