我给了一个向量

  vector<string> inputArray = { "aba","aa","ad","vcd","aba" };


我想返回这个仅包含最长长度字符串的向量,在这种情况下,我只想返回{"aba","vcd","aba"},所以现在我要删除长度不等于最高长度的元素。

vector<string> allLongestStrings(vector<string> inputArray) {

int length = inputArray.size();
int longstring = inputArray[0].length();
int count = 0;

vector<string> result;

for (int i = 0; i < length; i++)
{
    if (longstring < inputArray[i].length())
    {
        longstring = inputArray[i].length();
    }
    count++;

}

for (int = 0; i<count;i++)
{
    if (inputArray[i].length() != longstring)
    {
        inputArray[i].erase(inputArray.begin() + i);
        count--;
        i--;
    }
}

return inputArray;


}

但我在此行的no instance of overloaded fucntion "std::basic_string<_Elem,_Traits,_Alloc>::erase[with_Elem=char,_Traits=std::char_traits<char>,_Alloc=std::allocator<char>]" matches the argument list"中收到此错误inputArray[i].erase(inputArray.begin()+i);

怎么了?

最佳答案

还有其他问题,但是此特定的编译器消息告诉您这不是从字符串中删除特定字符的正确方法。

但是,通过阅读OP中的问题,我们看到您想从向量中删除字符串。要解决该特定错误,只需更改

inputArray[i].erase( /*character position(s) in the string*/ )




inputArray.erase( /*some position in the array*/ )


或者,您可以修复它,以便它在inputArray [i]所表示的字符串中使用迭代器从该字符串中实际删除字符,这当然不是您要执行的操作。关键是,错误消息是因为您使用错误的迭代器类型,因为您认为自己正在使用向量,但实际上却告诉它使用从向量中提取的字符串。

然后,您将进行编译,并获得其他注释中已经涵盖的其他问题。

关于c++ - 如何从std::vector <string>删除元素的长度(删除不起作用),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55300502/

10-15 00:26
查看更多