相关疑难解决方法(0)

移动向量会使迭代器失效吗?

如果我有一个迭代到载体a,然后我布展构建体或移动指派矢量ba,是否仍迭代器指向同一元件(现在矢量b)?这就是我在代码中的意思:

#include <vector>
#include <iostream>

int main(int argc, char *argv[])
{
    std::vector<int>::iterator a_iter;
    std::vector<int> b;
    {
        std::vector<int> a{1, 2, 3, 4, 5};
        a_iter = a.begin() + 2;
        b = std::move(a);
    }
    std::cout << *a_iter << std::endl; // Is a_iter valid here?
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是否a_iter仍然有效的,因为a已移入b,或者是通过招无效的迭代器?作为参考,std::vector::swap 不会使迭代器无效.

c++ iterator c++11

66
推荐指数
3
解决办法
3834
查看次数

std :: vector :: swap会使迭代器失效吗?

如果我交换两个向量,它们的迭代器是否仍然有效,现在只是指向"其他"容器,或者迭代器是否会失效?

那是,给定:

using namespace std;
vector<int> x(42, 42);
vector<int> y;
vector<int>::iterator a = x.begin(); 
vector<int>::iterator b = x.end();

x.swap(y);

// a and b still valid? Pointing to x or y?
Run Code Online (Sandbox Code Playgroud)

似乎std没有提到这个:

[n3092 - 23.3.6.2]

void swap(vector<T,Allocator>& x);

效果:将*的内容和容量()与x的内容和容量()进行交换.

请注意,因为我在VS 2005上,我也对迭代器调试检查等的影响感兴趣(_SECURE_SCL)

c++ iterator stl visual-c++

39
推荐指数
2
解决办法
4079
查看次数

移动std :: vector时是否需要保留容量?

请考虑以下代码:

std::vector vec;
vec.reserve(500);
size_t cap = vec.capacity();

std::vector newVec = std::move(vec);
assert(cap == newVec.capacity());
Run Code Online (Sandbox Code Playgroud)

在几乎任何你遇到的实现中,这都可行.我不关心实现什么.我想知道标准需要什么.移动的vector容量是否与原始容量相同?或者断言触发器?

c++ stdvector language-lawyer move-semantics c++11

18
推荐指数
2
解决办法
581
查看次数