向量中的擦除功能

时间:2012-01-15 12:24:23

标签: c++ vector

我正在尝试学习c ++。没有delSong函数,这段代码编译得很好。但有了它,它将无法编译。我无法弄清楚我做错了什么......: - /

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Jukebox {

public:
  void addSong(string artist, string title, string filename) {
    songCounter++;
    song s {songCounter, artist, title, filename};
    Songs.push_back(s);
  }

  void delSong(int pos) {
    Songs.erase(pos);
  }

  void printSong(int pos) {
    cout << Songs[pos].no << ". ";
    cout << Songs[pos].artist << " - ";
    cout << Songs[pos].title << " : ";
    cout << Songs[pos].filename << endl;
  }

  void printSongs() {
    for (int i = 0; i < Songs.size(); i++) {
      printSong(i);
    }
  }

  Jukebox(): songCounter(0) {}

private:
  int songCounter;
  struct song {
    int no;
    string artist;
    string title;
    string filename;
  };
  vector<song> Songs;
};

int main() {
  Jukebox jbox;
  jbox.addSong("U2", "Magnificent", "U2-Magnificent.mp3");
  jbox.addSong("Sting", "Englishman in New York", "Sting-Englishman_in_New_York.mp3");
  jbox.addSong("U2", "One", "U2-One.mp3");
  jbox.printSongs();
  return 0;
}

2 个答案:

答案 0 :(得分:6)

了解erase的定义方式:

http://www.cplusplus.com/reference/stl/vector/erase/

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

它将迭代器而不是索引作为参数。而不是

Songs.erase(5);

尝试:

Songs.erase(Songs.begin() + 5);

begin()返回一个迭代器,+5将其移动到要删除的位置。

答案 1 :(得分:2)

std::vector<T>::erase()函数不带索引。它需要一个迭代器。如果要从具有随机访问容器的索引(例如std::vector<T>)获取迭代器,您可以使用begin()并添加相应的偏移量:

this->Songs.erase(this->Songs.begin() + pos);