我还从编程原则和实践中复制了精确的代码,但没有效果。当我尝试使用std::sort(word)
或sort(word)
时,会收到一条错误消息
<source>: In function 'int main()':
<source>:13:14: error: no matching function for call to 'sort(std::vector<std::__cxx11::basic_string<char> >&)'
13 | std::sort(words);
| ~~~~~~~~~^~~~~~~
[...]
守则:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> words;
for(std::string temp; std::cin >> temp;){
words.push_back(temp);
}
std::cout << "Number of words: " << words.size() << "\n";
std::sort(words);
for(int i=0; i < words.size(); i++){
if(i == 0; words[i-1]!=words[i]){
std::cout << words[i] << "\n";
}
}
}
发布于 2021-07-07 09:41:41
代码中有两个问题:
sort
的用法是错误的,是std::sort(words.begin(), words.end())
。这应该写在你的书里或者你的学习材料里。--在第一次迭代期间,
if (i == 0; words[i-1]!=words[i])
是0,因此您访问的是超出界限的words[-1]
,它最多只会触发一些错误消息。;
在这里也没有意义。--你可能想要这个:
for (size_t i = 0; i < words.size() - 1; i++) {
if (words[i] != words[i + 1]) {
std::cout << words[i] << "\n";
}
}
发布于 2021-07-07 09:57:04
排序函数接受2个或3个变量。前2种是用于开始和结束索引。在本例中,它们是words.begin()和words.end()
因此,您的第13行(有错误)应该是:
std::sort(words.begin(),words.end());
第三个参数可以用来指定排序的类型。例如,
std::sort(words.begin(),words.end(),greater<int>());
将向量按反向顺序排序。
https://stackoverflow.com/questions/68283467
复制相似问题