按值传递容器是否会使迭代器无效?

Does passing containers by value invalidate iterators?(按值传递容器是否会使迭代器无效?)
本文介绍了按值传递容器是否会使迭代器无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些示例代码:

#include <iostream>
#include <vector>

template <typename T>
std::vector<typename T::iterator> f(T t)
{
        std::vector<typename T::iterator> v;
        for (auto i = t.begin(); i != t.end(); ++i)
        {
                v.push_back(i);
        }
        return v;
}

template <typename T>
void print(const std::vector<T>& v)
{
        for (auto i = v.begin(); i != v.end(); ++i)
        {
                std::cout << **i << ' ';
        }
        std::cout << std::endl;
}

int main()
{
        std::vector<int> v{1, 2, 3};
        print(f(v));
        std::vector<std::vector<int>::iterator> itervec = f(v);
        print(itervec);
}

在 ideone 上的输出是:

1 2 3 
163487776 2 3 

问题

如果我将 f(T t) 更改为 f(T& t),则输出符合预期.我假设因为我正在使用容器的副本,从技术上讲,我在向量上推回的迭代器与我在 main.js 中创建的向量不同.这个对吗?我注意到的一件事是 print(f(v)); 按预期打印 1 2 3 但是一旦我将它分配给 itervec第一个迭代器变成垃圾,这一切都依赖于实现吗?

If I change f(T t) to f(T& t) the output is as expected. I'm assuming because I am working with copies of containers, technically the iterators I am pushing back on the vector are not the same as the vector I created in main. Is this correct? The one thing I noticed is print(f(v)); prints 1 2 3 as expected but as soon as I assign it to itervec the first iterator becomes garbage, is this all implementation dependent?

推荐答案

是的,迭代器是迭代器只对函数中的本地对象v有效f,而在f结束时,v超出范围被销毁,迭代器无效.

Yes, the iterators are iterators only valid for the local object v in the function f, and at the end of f, v goes out of scope and is destroyed, and the iterators are invalid.

您必须通过引用(或指针或其他方式)传递向量,以便您存储的迭代器是调用者传入的原始对象的迭代器,而不是存储在局部变量中的临时副本.

You have to pass the vector by reference (or pointer or whatever) so that the iterators you store are the iterators for the original object that the caller passes in, not for a temporary copy stored in a local variable.

您看到的行为是未定义的,所以它恰好正确地打印了前三个和后两个.

The behaviour you are seeing is undefined, so it just happens to print the first three and last two correctly.

这篇关于按值传递容器是否会使迭代器无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)