在向量c ++中获取字符串数

Cyb*_*hot 2 c++ string stl vector count

我有这个载体

vector <string> data

data = ["this is", "data that", "is in", "this is", "vector", "vector", "vector"]
Run Code Online (Sandbox Code Playgroud)

我如何获得一个矢量(或2D数组)来删除重复项,而不是每个第i个条目的计数?

 results = [("this is", 2), ("data that", 1), ("is in", 1), ("vector", 3)]
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 5

直接的解决方案是将唯一值及其计数累积到地图中:

std::map<std::string, std::size_t> results;
std::for_each(begin(data), end(data), [&](std::string const& s)
{
    ++results[s];
});
Run Code Online (Sandbox Code Playgroud)

这具有线性(n lg n)时间复杂度,但因为它必须复制每个不同的字符串值,所以它可能相当昂贵.您还可以对列表进行排序,然后计算每个值的数量,如果您具有移动感知实现,则可能会更好std::string.