Clonagem de vetores
Diferente de R, C++ usa um sistema de cópia por referência, o que significa que, se você copiar uma variável e fizer alterações na cópia, essas alterações também acontecerão no original.
// [[Rcpp::export]]
NumericVector always_returns_two(NumericVector x) {
// Make a copy
NumericVector y = x;
// Modify the copy
y[0] = 2;
// The changes also happen in the original
return x[0];
}
Para evitar esse comportamento, você precisa usar a função clone() para copiar os dados subjacentes da variável original para a nova variável. A sintaxe é y = clone(x).
Neste exercício, definimos duas funções para você:
change_negatives_to_zero(): Recebe um vetor numérico, modifica substituindo números negativos por zero e, em seguida, retorna tanto o vetor original quanto a cópia.change_negatives_to_zero_with_cloning(): Faz a mesma coisa que acima, mas clona o vetor original antes de modificá-lo.
Este exercicio faz parte do curso
Otimizando código R com Rcpp
Instruções do exercicio
- Complete a definição da função
change_negatives_to_zero()definindothe_originalcomothe_copy. - Complete a definição da função
change_negatives_to_zero_with_cloning()definindothe_copycomo o clone dethe_original. - Leia o conteúdo do console para comparar a saída de cada função.
exercicio interativo prático
Tente este exercicio completando este código de exemplo.
#include
using namespace Rcpp;
// [[Rcpp::export]]
List change_negatives_to_zero(NumericVector the_original) {
// Set the copy to the original
NumericVector the_copy = ___;
int n = the_original.size();
for(int i = 0; i < n; i++) {
if(the_copy[i] < 0) the_copy[i] = 0;
}
return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}
// [[Rcpp::export]]
List change_negatives_to_zero_with_cloning(NumericVector the_original) {
// Clone the original to make the copy
NumericVector the_copy = ___;
int n = the_original.size();
for(int i = 0; i < n; i++) {
if(the_copy[i] < 0) the_copy[i] = 0;
}
return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}
/*** R
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero(x)
# Need to define x again because it's changed now
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero_with_cloning(x)
*/