我只展示我的功能,因为我相信问题出在我的for循环中。
DataStoreVectors::DataStoreVectors() {
}
void DataStoreVectors::addItem(string item1, int item2) {
videoGame.push_back(item1);
gameSize.push_back(item2);
}
void DataStoreVectors::listItems()
{
vector <string>::iterator pv;
vector <int>::iterator px;
for (pv = videoGame.begin(); pv < videoGame.end(); pv++)
{
for (px = gameSize.begin(); px < gameSize.end(); px++)
cout << *pv << " " << *px << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试打印出两个数组中的数据时,它会打印出每个视频游戏的名称大约 6 次,并将我的int值分配给它们,如下所示:
Valorant 8
Valorant 70
Valorant 50
Valorant 1
Valorant 26
Valorant 35
Fortnite 8
Fortnite 70
Fortnite 50
Fortnite 1
Fortnite 26
Fortnite 35
Doom Eternal 8
Doom Eternal 70
Doom Eternal 50
Doom Eternal 1
Doom Eternal 26
Doom Eternal 35
Minecraft 8
Minecraft 70
Minecraft 50
Minecraft 1
Minecraft 26
Minecraft 35
Apex Legends 8
Apex Legends 70
Apex Legends 50
Apex Legends 1
Apex Legends 26
Apex Legends 35
Control 8
Control 70
Control 50
Control 1
Control 26
Control 35
Run Code Online (Sandbox Code Playgroud)
这可能吗?做一个结构会更好吗?我试图找出并排打印出两个向量的正确方法。
保持迭代器的位置同步非常简单。只需在 for 循环中添加另一个增量,如下所示:
vector <int>::iterator px = gameSize.begin(); // << Add this
for (pv = videoGame.begin(); pv < videoGame.end(); pv++, px++)
// ^^^^^^ Add this
Run Code Online (Sandbox Code Playgroud)
确保两个向量具有相同的大小,或者px指向的向量至少比另一个 ( videoGame) 大。
您可以使用 range-v3 zip view。
for (auto [game, size] : ranges::views::zip(videoGame, gameSize))
{
std::cout << game << " " << size << std::endl;
}
Run Code Online (Sandbox Code Playgroud)