繁体   English   中英

多地图迭代器不起作用

[英]multimap iterator not working

我有一个Playlist类,该类具有一个带有Tracks的向量,每个Track都有一个multimap<long, Note>作为数据成员。

class Track {
private:
    multimap<long, Note> noteList;
}

使用迭代器访问轨道没有问题,因此这里的这一部分工作正常:

vector<Track>::iterator trackIT;
    try{
        for(noteIT = trackIT->getNoteList().begin(); noteIT != trackIT->getNoteList().end(); noteIT++){
            cout << "---" << noteIT->second.getName() << endl;
        }
    }catch (int e){
        cout << "exception #" << e << endl;
    }

接下来,我要迭代每个TrackNotes 但是从这部分开始,所有输出都将停止。 因此,我只能看到第一个曲目的名称。 之后的任何提示都不会显示,并且编译器不会给我任何错误。 甚至try catch块内的cout也无法正常工作。

vector<Track>::iterator trackIT;
multimap<long, Note>::iterator noteIT;
for(trackIT = this->playlist.getTracklist().begin(); trackIT < this->playlist.getTracklist().end(); trackIT++){
    cout << trackIT->getTrackName() << endl;

    for(noteIT = trackIT->getNoteList().begin(); noteIT != trackIT->getNoteList().end(); noteIT++){
        cout << "---" << noteIT->second.getName() << endl;
    }
}
cout << "random cout that is NOT shown" << endl; // this part doesn't show up in console either

另外,我用于添加Note对象的Track类中的方法如下所示:

void Track::addNote(Note &note) {
    long key = 1000009;
    this->noteList.insert(make_pair(key, note));
}

// I'm adding the notes to the track like this:
Note note1(440, 100, 8, 1, 1);
note1.setName("note1");
synthTrack.addNote(note1);

有什么想法为什么迭代器不起作用?

更改

noteIT < trackIT->getNoteList().end()

noteIT != trackIT->getNoteList().end()

并非所有迭代器都支持小于/大于比较。

如果您拥有c ++ 11,则可以使用基于范围的for循环:

for (Note& note : trackIT->getNoteList())

或者您可以使用BOOST_FOREACH

BOOST_FOREACH (Note& note, trackIT->getNoteList())

如果您真的要对轨道键进行硬编码,则地图中将永远只有一个轨道,因为std :: map存储唯一的键...

long key = 1000009; //If yo are really doing this, this key is already inserted so it will fail to insert more.

另外,如果您想使用更优雅的方法,可以使用函数对象。

struct print_track
{
    void operator()(const Track& track)
    {
        cout << track.getTrackName() << endl;
        std::for_each(track.getNoteList().begin(), track.getNoteList().end(), print_track_name());
    }
};

struct print_note_name
{
    void operator()(const std::pair<long,Note>& note_pair)
    {
       cout << "---" << note_pair.second.getName() << endl;
    }
};

//In use...
std::for_each(playlist.getTracklist().begin(), playlist.getTracklist.end(), print_track());

您尚未显示getTrackListgetNoteList的定义,但是人们常犯一个错误-如果返回容器的副本而不是对其的引用,则迭代器将指向不同的容器,从而无法进行比较。 不仅如此,由于容器是临时的,因此对迭代器的任何使用都会导致未定义的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM