Vector 容器怎么删除指定数据问题。不清楚该数据在vector里的索引

千年捞菜 2014-08-15 10:44:27
vector<int> v_int;
现在我只知道容器里有三个值,分别为100,200,300,现在我要删除200,但我不知道其索引,就不能用erase函数了,求解答怎么获得指定数据的索引,然后调用erase函数啊
...全文
177 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
mymtom 2014-08-15
  • 打赏
  • 举报
回复
find ? 遍历? 请用remove

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int
main(int argc, char *argv[])
{
    vector<int> vi;
    vector<int>::const_iterator it;

    vi.push_back(100);
    vi.push_back(200);
    vi.push_back(300);

    for (it = vi.begin(); it != vi.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    vi.erase(remove(vi.begin(), vi.end(), 200), vi.end());

    for (it = vi.begin(); it != vi.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}
赵4老师 2014-08-15
  • 打赏
  • 举报
回复
引用 3 楼 a350277864 的回复:
[quote=引用 1 楼 a345485527 的回复:] for循环遍历一下呗 或者STL里的find类算法也行
还以为有直接的函数可以得到呢,还是要for循环来找啊,费时间,怎么没有个函数根据数据得到索引呢 呵呵[/quote] 可以考虑改用map
Pump天天学习 2014-08-15
  • 打赏
  • 举报
回复
引用 3 楼 a350277864 的回复:
[quote=引用 1 楼 a345485527 的回复:] for循环遍历一下呗 或者STL里的find类算法也行
还以为有直接的函数可以得到呢,还是要for循环来找啊,费时间,怎么没有个函数根据数据得到索引呢 呵呵[/quote] find STL的泛型算法 上网搜一下 不过复杂度和自己遍历一遍差不多
千年捞菜 2014-08-15
  • 打赏
  • 举报
回复
引用 1 楼 a345485527 的回复:
for循环遍历一下呗 或者STL里的find类算法也行
还以为有直接的函数可以得到呢,还是要for循环来找啊,费时间,怎么没有个函数根据数据得到索引呢 呵呵
风行踩火轮 2014-08-15
  • 打赏
  • 举报
回复
find应该可以吧,要么就遍历一下,直接删除就可以了,知道值就很好删除
Pump天天学习 2014-08-15
  • 打赏
  • 举报
回复
for循环遍历一下呗 或者STL里的find类算法也行
千年捞菜 2014-08-15
  • 打赏
  • 举报
回复
引用 6 楼 mymtom 的回复:
find ? 遍历? 请用remove

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int
main(int argc, char *argv[])
{
    vector<int> vi;
    vector<int>::const_iterator it;

    vi.push_back(100);
    vi.push_back(200);
    vi.push_back(300);

    for (it = vi.begin(); it != vi.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    vi.erase(remove(vi.begin(), vi.end(), 200), vi.end());

    for (it = vi.begin(); it != vi.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}
这个我试了可以,但是最后改成了map了,代码量少了很多,谢谢你了
千年捞菜 2014-08-15
  • 打赏
  • 举报
回复
引用 5 楼 zhao4zhong1 的回复:
[quote=引用 3 楼 a350277864 的回复:] [quote=引用 1 楼 a345485527 的回复:] for循环遍历一下呗 或者STL里的find类算法也行
还以为有直接的函数可以得到呢,还是要for循环来找啊,费时间,怎么没有个函数根据数据得到索引呢 呵呵[/quote] 可以考虑改用map[/quote] map使用成功,比较简单,谢谢

64,680

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧