我正在尝试创建一个方法,该方法采用ArrayList并将其中的所有内容加倍。例如,如果ArrayList单词存储了[“ hello”,“ there”],则应输出[“ Hello”,“ Hello”,“ there”,“ there”]。我已经做出了一种我认为应该可行的方法,但是没有奏效。谁能告诉我我错了哪里?我将不胜感激!我的代码在下面。
public ArrayList<String> doubleList(ArrayList<String> words) {
ArrayList<String> newWords = new ArrayList<String>();
for (int i = 0; i < words.size(); i++) {
newWords.add(words.get(i));
newWords.add(words.get(i));
}
return newWords;
}
答案 0 :(得分:2)
好吧,我尝试运行您的方法,并且效果很好。
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
words.add("a");
words.add("b");
words.add("c");
ArrayList<String> doubledList = doubleList(words);
System.out.println(doubledList);
}
public static ArrayList<String> doubleList(ArrayList<String> words) {
ArrayList<String> newWords = new ArrayList<>();
for (int i = 0; i < words.size(); i++) {
newWords.add(words.get(i));
newWords.add(words.get(i));
}
return newWords;
}
}
我得到的结果如下:
[a,a,b,b,c,c]
答案 1 :(得分:1)
我怀疑您的网站可能不喜欢您正在创建新存储。我们如何像这样进行一些更改?
$ cat transfer.cu
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include "transfer.h"
#include <iostream>
#include <cstdio>
#include <thrust/copy.h>
#include <vector>
__global__ void k(float *data, size_t ds){
for (int i = 0; i < ds; i++) printf("%f,", data[i]);
}
// thrust vectors (global)
std::vector<thrust::host_vector<float> > trianglethrust_host;
std::vector<thrust::device_vector<float> > trianglethrust_device;
void trianglesToGPU_thrust(const float *mesh, float** triangles) {
//create vectors
trianglethrust_host.resize(1);
trianglethrust_device.resize(1);
// fill host vector
size_t i = 0;
while (mesh[i] != 0.0f) {
trianglethrust_host[0].push_back(mesh[i++]);
}
// copy to GPU by assigning host vector to device vector, like in the Thrust documentation
trianglethrust_device[0] = trianglethrust_host[0];
// save raw pointer
*triangles = (float*)thrust::raw_pointer_cast(trianglethrust_device[0].data());
}
void do_global_work(float** triangles){
std::cout << "from device vector:" << std::endl;
thrust::copy(trianglethrust_device[0].begin(), trianglethrust_device[0].end(), std::ostream_iterator<float>(std::cout, ","));
std::cout << std::endl << "from kernel:" << std::endl;
k<<<1,1>>>(*triangles, trianglethrust_device[0].size());
cudaDeviceSynchronize();
std::cout << std::endl;
}
void finish(){
trianglethrust_host.clear();
trianglethrust_device.clear();
}
$ nvcc -c transfer.cu
$ g++ -o test main.o transfer.o -L/usr/local/cuda/lib64 -lcudart
$ ./test
from device vector:
0.1,0.2,0.3,
from kernel:
0.100000,0.200000,0.300000,
$