使用 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( 是计算数组大小的宏(
由于这些向量是类的属性,因此在构造函数上启动它们是没有意义的。
我正在与这个问题斗争一段时间,大多数"解决方案"都涉及切换到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。
相关文章:
- 将二维矢量传递给类
- 将值从二维数组输出到文本文件
- 我在二维向量中是否正确分配了内存
- 带结构的二维矢量:如何存储元素
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 使用 C++98 标准填充二维静态向量
- 如何在编译时初始化静态二维数组
- 二维静态和动态数组传递
- 静态声明的二维数组C++为类的数据成员
- 初始化静态二维数组
- 二维静态地图的初始化
- c++将静态二维双精度数组转换为双精度**