use*_*641 2 c++ arrays variable-assignment
我对Java非常熟悉,这是允许的.然而,看起来它不适用于C++.我在尝试分配valuesToGrab = updatingValues;时收到"无效的数组赋值".
//these are class attributes
int updatingValues[361] = {0};
int valuesToGrab[361] = {0};
//this is part of a function that is causing an error.
for (unsigned int i=0; i < 10; i++) {
//this fills values with 361 ints, and num_values gets set to 361.
sick_lms.GetSickScan(values,num_values);
//values has 361 ints, but a size of 2882, so I copy all the ints to an array
//of size 361 to "trim" the array.
for(int z = 0; z < num_values; z++){
updatingValues[z] = values[z];
}
//now I want to assign it to valuesToGrab (another program will be
//constantly grabbing this array, and it can't grab it while it's being
//populated above or there will be issues
valuesToGrab = updatingValues; // THROWING ERROR
}
Run Code Online (Sandbox Code Playgroud)
我不想迭代更新VALal并将其逐个添加到valuesToGrab,但如果我必须,我会.有没有办法用C++在一个函数中分配它?
谢谢,
用C++复制的标准习惯用法是
#include <algorithm>
...
std::copy(values, values+num_values, updatingValues);
Run Code Online (Sandbox Code Playgroud)
确保updatingValues足够大或者你会超支并且会发生坏事.
那就是说在C++中我们通常使用std :: vector来完成这类任务.
#include <vector>
...
std::vector<int> updatingValues=values; //calls vectors copy constructor
Run Code Online (Sandbox Code Playgroud)
我向量执行数组所做的一切(包括C++ 11中的静态初始化),但是有一个很好的定义接口.with iterators,size,empty,resize,push_back等等.
http://en.cppreference.com/w/cpp/algorithm/copy
http://en.cppreference.com/w/cpp/container/vector
编辑值得注意的是,您可以组合矢量和数组.
std::vector<int> vect(my_array, my_array+10);
//or
std::vector<int> another_vector;
...
another_vector.assign(my_array, my_array+10);//delayed population
Run Code Online (Sandbox Code Playgroud)
反之亦然
std::copy(vect.begin(), vect.end(), my_array); //copy vector into array.
Run Code Online (Sandbox Code Playgroud)