将std :: vector的副本附加到自身的结尾 [英] Append a copy of std::vector to the end of itself
问题描述
我试图创建一个字符串向量的副本,并将其附加到其原始向量的结尾,即复制其内容。示例:
I am trying to make a copy of a vector of string and append it to the end of its original vector, i.e. duplicating its contents. Example:
Input : vector<string> s = {"abc", "def"}
Output: vector<string> s = {"abc", "def", "abc", "def"}
使用insert方法,即
I was using the insert method, i.e.
s.insert(s.end(), s.begin(), s.end());
但是,这会显示与编译器相关的结果。在,LLVM ang,它给了我预期的答案。
However, this exhibits compiler-dependent results. In, LLVM clang, it gave me the expected answer.
使用GCC它给了我
Output: vector<string> s = {"abc", "def", "", ""}
这里是上面程序的ideone.com链接: http://ideone.com/40CH8q
Here is the ideone.com link for the program above: http://ideone.com/40CH8q
推荐答案
虽然它可以用迭代器完成,一个安全的选择是避免它们:
Although it can possibly be done with iterators, a safe alternative is to avoid them:
size_t size = v.size(); // Of course we shouldn't access .size() in the loop...
v.reserve(size * 2); // Preallocation. Thanks @Ali for this performance hint
for (size_t i = 0; i < size; ++i)
v.push_back(v[i]);
一般来说,使用迭代器同时修改数据结构你应该仔细阅读迭代器是无效的,当它是安全的重新使用旧的迭代器修改后。因此,使用旧方法来遍历随机访问序列有时是有意义的:使用索引变量。
In general, working with iterators while also modifying the data structure (not only its elements) is dangerous; you should read carefully when iterators are invalidated and when it's safe to reuse old iterators after a modification. Thus, it sometimes makes sense to use the "old" method to iterate through a random-access sequence: using an index variable.
这篇关于将std :: vector的副本附加到自身的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!