c++ - 使用迭代器向 vector 插入元素没有效果

标签 c++ vector iterator dereference

请查看下面的 MRE:

#include <iostream>
#include <vector>
#include <iterator>

void display(const std::vector<std::string> &v){
    for(int i = 0; i < v.size(); i++){
        std::cout << v[i] << " ";
    }
    std::cout << std::endl;
}

int main(){
    std::vector<std::string> vect1;
    std::vector<std::string>::iterator i1 = vect1.begin();

    vect1.push_back("Test");
    display(vect1);
    std::cout << *i1 << std::endl;
    vect1.insert(i1, "Apple");
    std::cout << vect1.size() << std::endl;
    display(vect1);

    return 0;
}

当我尝试向 vect1 添加新元素时使用insert函数 vector 内容保持不变(根据 display 函数输出)。我在这里缺少什么吗?

最佳答案

迭代器

i1=vect1.begin();
如果 size 的值大于 0,则在将新元素添加到 vector 的 for 循环之后,

变得无效。否则这个语句

cout<<*i1<<endl;

将调用未定义的行为。

将此语句移到 for 循环之后。

i1=vect1.begin();

if ( !vect1.empty() ) cout<<*i1<<endl;

cout<<endl<<endl<<"***Inserting the string (Apple) At Index 1"<<endl;
vect1.insert(i1,"Apple");

请注意该消息

"***Inserting the string (Apple) At Index 1"

不正确。由于迭代器 it 指向 vector 的第一个元素,因此字符串存储在索引 0 处。也就是说,您应该使用 message

"***Inserting the string (Apple) At Index 0"

关于c++ - 使用迭代器向 vector 插入元素没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74576087/

相关文章:

java - 覆盖循环数组中的迭代器

c++ - 如何从cin获取超过1个单词的输入

使用流和缓冲区的 C++ 最佳实践

c++ - 要搜索一个值然后从对象数组中删除包含它的对象?

R:将列表中每个 < 1 的元素乘以 10,直到该元素 > 1

c++ - C++ 中的集合和 xmemory

c++ - 如何有效地将一系列值插入到 std::deque 中?

c++ - 如何使用 Rose 编译器打印函数级调用图

C++ 将 3 维(点) vector 旋转到不同的对象空间

ruby - Ruby中的高阶迭代器?