【发布时间】:2021-11-16 23:54:58
【问题描述】:
我目前正在阅读 Stanley Lippman 的 C++ Primer。第 10 章介绍了泛型算法。
例如std::sort、std::unique 和std::vector 成员函数erase 应用于删除向量中的重复元素。
要查看 std::unique 如何重新排列向量元素,我尝试打印每个元素,只是发现并非所有元素都被打印。然而,调用.size() 表明向量的大小与预期的一样没有变化。
编译程序后:
clang++ -std=c++11 -o elimDubs elimDubs.cc
并用
调用程序./elimDubs the quick red fox jumps over the slow red turtle
程序打印
Size after std::unique: 10
fox jumps over quick red slow the turtle the
这只是 10 个元素中的 9 个。 (red 不见了)
为什么?对于程序来说,这并不重要,因为随后调用erase 无论如何都用于删除重复的元素,但仍然让我恼火的是缺少元素或至少没有打印出来。
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
void elimDubs( std::vector<std::string> &words )
{
std::sort( words.begin(), words.end() );
auto end_unique = std::unique( words.begin(), words.end() );
std::cout << "Size after std::unique: "
<< words.size() << std::endl;
for ( const auto &el : words )
std::cout << el << " ";
std::cout << std::endl;
}
int main(int argc, char **argv)
{
std::vector<std::string> sentence;
if ( argc < 2 )
return -1;
std::copy( argv + 1, argv + argc,
std::back_inserter(sentence) );
elimDubs( sentence );
}
【问题讨论】:
-
这并没有解决问题,但是
sentence可以直接用std::vector<std::string> sentence(argv + 1, argv + argc);初始化。