0

我正在尝试将字符串单词插入向量中,然后让它发生。我在这里做了重要的工作。问题在于计算每个字符出现次数低于代码计数的单词。

可能我将字符插入向量而不是单词。我试图从谷歌获得解决方案,但没有得到我想要的。

#include <iostream>
#include <algorithm>
#include <map>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <unordered_map>

std::pair < int, std::string > mytransform(const std::pair < std::string, int >p)
{
    return std::pair < int, std::string > (p.second, p.first);
}

int main(int argc, char *argv[])
{
    std::string result_string=argv[1];
    std::istringstream iss;
    std::multimap < int, std::string, std::greater < int >>dst;
    std::multimap < int, std::string >::iterator rec;
    typedef std::unordered_map<std::string,int> occurrences;
    occurrences s1;
    std::vector<std::string> most;
    std::map < std::string, int >src;

    std::vector<std::string> writable(result_string.size() + 1);
    std::copy(result_string.begin(), result_string.end(), writable.begin());

    for (std::vector < std::string >::iterator it = writable.begin(); it != writable.end(); it++)
    ++src[*it];

    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), mytransform);
    std::multimap < int, std::string >::iterator it = dst.begin();

   for (it = dst.begin(); it != dst.end(); ++it)
    std::cout << it->second << ":" << it->first << std::endl;

    return 0;
}

输出:

technoworld@ubuntu:~/Videos/LinSocket/Modular$ ./q "one one two"
o:3
 :2
e:2
n:2
t:1
w:1
:1

而是应该是:

technoworld@ubuntu:~/Videos/LinSocket/Modular$ ./q "one one two"
one:2
two:1
4

3 回答 3

3
#include <iostream>
#include <map>
#include <sstream>

int main() {
    std::string input =  "one one two";
    std::istringstream in(input);
    std::map<std::string, unsigned> counter;
    std::string s;
    while(in >> s) {
        ++counter[s];
    }
    for(const auto& kv: counter) {
        std::cout << kv.first << ": " << kv.second << std::endl;
    }
    return 0;
}
于 2013-09-03T11:09:22.873 回答
2

您正在为字符串使用迭代器,因此您遍历字符。相反,对字符串进行拆分并迭代结果中的字符串

std::string word;

while( getline(writable, word, ' ') )
{
   ++src[word];
}

欲了解更多信息,请阅读此处

于 2013-09-03T11:02:58.937 回答
1

您只是将字符推入writable矢量和许多不必要的东西

如果您尝试将其作为单个字符串使用:

std::vector<std::string> writable ;

std::stringstream ss(result_string);
std::string item;
while (std::getline(ss, item, ' ')) {
    writable.push_back(item);
}


for (std::vector < std::string >::iterator it = writable.begin();
       it != writable.end(); it++)
 ++src[*it];

或者为什么不简单地:(这不需要引用您的命令行参数)

    for(int i=0;i<argc;++i)
     ++src[std::string(argv[i])];
     std::multimap < std::string,int >::iterator it ;

   for (it = src.begin(); it != src.end(); ++it)
     std::cout << it->second << ":" << it->first << std::endl;
于 2013-09-03T11:14:16.600 回答