在向量中查找特定元素

时间:2011-11-04 01:55:31

标签: vector iterator find

我有一个班级团队,其中包含足球队的信息。我需要阅读一个文件并将每个独特的团队添加到矢量季节。

//循环以确定独特的团队

    if(season.size() <= 1)
        {
            season.push_back(new_team);
            cout << "First team added!" << endl;
        }

    vector<team>::iterator point;
    point = find(season.begin(), season.end(), new_team);
    bool unique_team = (point != season.end());
    if(unique_team == true && season.size()>1)
        {
            season.push_back(new_team);
            cout << "New team added!" << endl;
        }

    cout << "# of Teams: " << season.size() << endl;
    system("pause");

为什么这不起作用的任何想法?我还是新手:-)所以请随意提出建设性的批评。

1 个答案:

答案 0 :(得分:1)

我认为你的逻辑可能有点偏差。当团队矢量的大小为0时,应该添加第一个团队。假设你的团队是整数的向量,insertTeam函数看起来像这样。

void Season::insertTeam(int team)
{
    if (teams.size() == 0)
    {
        teams.push_back(team);
        cout << "First team " << team << " added!" << endl;
    }
    else
    {
        vector<int>::iterator point;
        point = find(teams.begin(), teams.end(), team);
        bool unique_team = (point == teams.end());
        if(unique_team == true && teams.size()>0)
        {
            teams.push_back(team);
            cout << "New team " << team << " added!" << endl;
        }
    }
}