C++ 移动迭代器和 int 向量

编程入门 行业动态 更新时间:2024-10-22 16:36:32
本文介绍了C++ 移动迭代器和 int 向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试理解移动迭代器.这是来自 en.cppreference/w/cpp/的示例代码迭代器/make_move_iterator

I am trying to understand the move iterator. This is the sample code from en.cppreference/w/cpp/iterator/make_move_iterator

#include <iostream> #include <list> #include <vector> #include <string> #include <iterator> int main() { std::vector<std::string> s{"one", "two", "three"}; std::vector<std::string> v1(s.begin(), s.end()); // copy std::vector<std::string> v2(std::make_move_iterator(s.begin()), std::make_move_iterator(s.end())); // move std::cout << "v1 now holds: "; for (auto str : v1) std::cout << "\"" << str << "\" "; //return one, two, three std::cout << "\nv2 now holds: "; for (auto str : v2) std::cout << "\"" << str << "\" "; //return one, two, three std::cout << "\noriginal list now holds: "; for (auto str : s) std::cout << "\"" << str << "\" "; //return nothing std::cout << '\n'; }

所以移动迭代器按预期移动.但是当我做了一些小改动时:

So the move iterator moves as expected. But when I made some minor changes:

std::vector<int> s{1, 2, 3}; std::vector<int> v1(s.begin(), s.end()); // copy std::vector<int> v2(std::make_move_iterator(s.begin()), std::make_move_iterator(s.end())); // move

尽管移动了

s 仍然引用 {1, 2, 3}.这有什么原因吗?

s still references {1, 2, 3} despite moving. Is there a reason for this?

推荐答案

这些输出是预期的.在第一种情况下,您正在移动 std::string,这是一个定义了移动构造函数的对象.在第二种情况下,您正在移动 int,它只是一个数字,因此没有移动构造函数.

Those outputs are expected. In the first case, you are moving an std::string, which is an object that has a move constructor defined. In the second case, you are moving an int, which is just a number and therefore doesn't have a move constructor.

当您从 std::string 移动时,您的程序会将底层指针指向一个动态字符数组,并将该指针放入新字符串中.

When you move from the std::string, your program will take the underlying pointer to a dynamic character array and place that pointer into the new string.

当你从 int 移动时,你的程序不会做任何特别的事情,因为没有成员变量或任何可以移动的东西.所以实际上复制和移动 int 之间没有区别.

When you move from the int, your program won't do anything special because there are no member variables or anything to move around. So really there is no difference between copying and moving an int.

希望这是有道理的!如果您需要更多解释,请发表评论,我会尽力回答:)

Hopefully this makes sense! Leave a comment if you'd like more explanation and I'll try my best to answer :)

更多推荐

C++ 移动迭代器和 int 向量

本文发布于:2023-07-30 00:31:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   迭代   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!