In this question, it is answered how a vector can be copied into a repeated field by using fMessage.mutable_samples() = {fData.begin(), fData.end()};
( and the other direction works too ).
But how about a partial copy? Would the below work?
std::copy(
fData.begin() + 3, fData.end() - 2,
fMessage.mutable_samples()->begin() + 3
);
In this scenario fMessage
has already allocated elements in the samples
field, and std::copy
would overwrite the items already present in fMessage
.
I created a program to test this, and it seems that using std::copy
works!
syntax = "proto3";
message messagetest{
repeated float samples = 6;
}
#include <iostream>
#include <vector>
#include "message.pb.h"
int main(){
std::vector<float> fData(10);
messagetest fMessage;
std::generate(fData.begin(),fData.end(),[&fMessage](){
static float num = 0.0;
num += 1.0;
fMessage.add_samples(0.0);
return num;
});
for(const float& f : fData)
std::cout << "[" << f << "]";
std::cout << std::endl;
std::copy(
fData.begin() + 3, fData.end() - 2,
fMessage.mutable_samples()->begin() + 3
);
for(const float& f : fMessage.samples())
std::cout << "[" << f << "]";
std::cout << std::endl;
return 0;
}
output:
[1][2][3][4][5][6][7][8][9][10]
[0][0][0][4][5][6][7][8][0][0]