【发布时间】:2020-07-01 13:34:11
【问题描述】:
我正在尝试将字符串向量中的元素移动到另一个字符串向量。目前我已经找到了一个解决方案,但它只适用于一个整数向量。我知道有一些明显的改变,比如矢量,但我正在努力弄清楚我还应该改变什么。下面是用于将一个整数向量移动到另一个整数向量的代码。
int main()
{
std :: vector <int> vec1 {1, 2, 3, 4, 5};
std :: vector <int> vec2 {7, 7, 7, 7, 7};
// Print elements
std :: cout << "Vector1 contains :";
for(int i = 0; i < vec1.size(); i++)
std :: cout << " " << vec1[i];
std :: cout << "\n";
// Print elements
std :: cout << "Vector2 contains :";
for(unsigned int i = 0; i < vec2.size(); i++)
std :: cout << " " << vec2[i];
std :: cout << "\n\n";
// std :: move function
// move first 4 element from vec1 to starting position of vec2
std :: move (vec1.begin(), vec1.begin() + 4, vec2.begin() + 1);
// Print elements
std :: cout << "Vector2 contains after std::move function:";
for(unsigned int i = 0; i < vec2.size(); i++)
std :: cout << " " << vec2[i];
std :: cout << "\n";
【问题讨论】:
-
你有
std::vector<std::string>或std::vector<char>或简单的std::string? -
是的,我知道我可以改变它,但我也必须改变 for 循环,但我不确定用什么替换它们
-
为什么要更改 for 循环?我不明白为什么(无论如何,for 循环只是打印结果,它们与将一个向量移动到另一个向量无关)。
-
如果我理解您想要正确执行的操作,您无需更改任何内容(除了向量),请参阅:wandbox.org/permlink/Zve8bOApXP1ep6eu
-
这里有一个提示,不要发布你认为有效的代码,而是发布你认为不起作用的代码。这样你会得到更多有用的帮助。