悟空又丢了 2023-01-13 19:52 采纳率: 0%
浏览 49

为什么这段程序,for 循环最后一个元素打印不出来?

int main()
{
    vector<string> words = {
        "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "the", "turtle", "the"
    };
    sort(words.begin(), words.end());  // 排序
    cout << words.size() << endl;
    for (auto &i : words)
        cout << i << " ";
    cout << endl;

    auto end_unique = unique(words.begin(), words.end()); // 重复元素放在后面
    cout << words.size() << endl;
    for (auto &i : words)
        cout << i << " ";
    cout << endl;

    return 0;
}

运行结果:

11
fox jumps over quick red slow the the the the turtle 
11
fox jumps over quick red slow the turtle the the

size 出来的大小都是正常的,但遍历打印就是少一个。

编译器:g++ 9.4.0

运行环境:Ubuntu 20.04

  • 写回答

2条回答 默认 最新

  • 流比 2023-01-13 20:47
    关注

    在使用 unique 函数之后,它将重复元素移到了末尾,因此在末尾的重复元素不会被遍历到。如果想要遍历所有元素,可以使用 end_unique 作为 for 循环的结束条件,而不是 words.end()。修改后代码如下:

    for (auto i = words.begin(); i != end_unique; ++i)
        cout << *i << " ";
    
    评论

报告相同问题?

问题事件

  • 专家修改了标签 1月13日
  • 创建了问题 1月13日

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀