简体   繁体   English

Pop_back向量中的元素

[英]Pop_back an element from a vector

I want to enter a string followed by an integer into two separate vectors, one for the string and one for the integers. 我想在两个单独的向量中输入一个字符串,后跟一个整数,一个用于字符串,一个用于整数。

If the entered string already exists in the vector for strings, I want to delete that last string entered. 如果输入的字符串已经存在于字符串向量中,那么我想删除最后输入的字符串。

while (std::cin >> tempName >> tempScore)
{
    if (tempName != "NoName" && tempScore != 0)
    {
        for (int i = 0; i < names.size(); i++)
        {
            if (tempName == names[i])
            {
                std::cout << "Error, duplicate name!" << std::endl;
                names.pop_back();
                scores.pop_back();
            }
        }
        names.push_back(tempName);
        scores.push_back(tempScore);
    }
    else
    {
        std::cout << "Wrong name and score!" << std::endl;
        break;
    }
}

This is a sample output using the above code. 这是使用上述代码的示例输出。

Enter a name followed by a score
foo 7
bar 9
foo 3
Error, duplicate name! 
^Z
foo 7
foo 3
Press any key to continue . . .

It deletes my previous input of tempName and enters the last entered name, which is the duplicate. 它将删除我先前输入的tempName并输入最后输入的名称,该名称是重复的名称。 I tried using vector.erase but this gives me a no instance of overloaded function . 我尝试使用vector.erase但这no instance of overloaded function给我no instance of overloaded function

Using a map will be more efficient in solving your problem ie logarithmic time complexity. 使用地图将更有效地解决您的问题, 对数时间复杂度。 It will also be concise and intuitive. 它将也是简洁和直观的。

std::map< string, int> mymap;
// your loop starts
mymap[tempName] = tempScore;
// loop ends 

If the string already is present, the set value statement will replace the value of string. 如果字符串已经存在,则设置值语句将替换字符串的值。

To erase from a vector use find and erase 要从向量中擦除,请使用finderase

vector<string>::const_iterator citr = std::find(names.cbegin(), names.cend(), tempName);
if (citr != names.cend())
{
    names.erase(citr);
}

To make your life easier, like @devsaw suggested, use a map so you can lookup more efficiently and remove both your string and integer entry in one call. 为了使您的生活更轻松(如@devsaw建议的那样),请使用地图,以便更高效地查找并在一次调用中删除字符串和整数项。

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

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