(已自行测试解决,cpp默认函数传递参数并非引用,导致函数输出的数组是副本,后面操作修改的不是原数组内容)虚幻引擎蓝图写了一个根据容器 type 类型和 index 交换两个数组的函数。其中有一个用容器类型展开选择的节点,直接写在函数内和折叠到宏能够正常执行交换(以下)


但是写进函数就不行了!没有报错,就是不起作用。改成执行函数也没用(如下)测试了遍历打印,函数输出的数组能够正常被打印出来,难道是设置整列元素无法正常获取数组引用?

百思不得其解,求指点!
(已自行测试解决,cpp默认函数传递参数并非引用,导致函数输出的数组是副本,后面操作修改的不是原数组内容)虚幻引擎蓝图写了一个根据容器 type 类型和 index 交换两个数组的函数。其中有一个用容器类型展开选择的节点,直接写在函数内和折叠到宏能够正常执行交换(以下)



百思不得其解,求指点!
关注引自强大而免费的微信小程序:皆我知道。
以下是根据您描述的情况编写的一个示例代码:
#include <iostream>
#include <vector>
#include <string>
// 定义一个交换数组元素的函数
template<typename T>
void swapArrayElements(std::vector<T>& arr, int index1, int index2) {
T temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
// 定义一个根据容器类型和索引交换数组元素的函数
template<typename Container, typename T>
void swapArrayElementsWithIndex(Container& container, int index1, int index2) {
std::vector<T>& arr = std::get<std::vector<T>>(container); // 从容器中获取指定类型的数组
swapArrayElements(arr, index1, index2); // 调用交换数组元素的函数
}
int main() {
// 测试示例
std::variant<std::vector<int>, std::vector<std::string>> container;
container = std::vector<int>{1, 2, 3, 4, 5};
int index1 = 2;
int index2 = 4;
swapArrayElementsWithIndex<decltype(container), int>(container, index1, index2); // 调用交换数组元素的函数
std::vector<int> result = std::get<std::vector<int>>(container);
for (const auto& num : result) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
以上代码使用了模板元编程的技巧,通过std::variant来实现不同类型的容器存储。在函数swapArrayElementsWithIndex中,首先从容器中获取指定类型的数组,然后调用swapArrayElements函数进行交换操作。最后,通过std::get从容器中获取交换完后的数组,并打印输出。