计算字符串向量中字符串的出现次数
count number of occurrences of a string in a vector of string
我的要求是计算字符串向量中字符串的出现次数。要搜索的字符串位于向量的第 0 个索引处。
我正在使用algorithm
标头中的内置count
函数,但遇到了一个奇怪的编译错误,我无法解决。
我的代码:
vector<string> a={"abc", "def", "abc"};
int cnt = count(a.begin(), a.end(), a[0]);
编译错误消息为:
count(std::vector<std::basic_string<char> >)':
error: no matching function for call to std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, __gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type&)'
int cnt = count(a.begin(), a.end(), a[0]);
有什么帮助吗?这里有什么问题?
您提到了算法库,但请确保您已添加#include <algorithm>
.
使用您的算法,它在代码上效果很好
#include <iostream> // std::cout
#include <algorithm> // std::count
#include <vector> // std::vector
#include <string> // std::vector
using namespace std;
int main () {
// counting elements in container:
vector<string> a {"abc", "def", "abc"};
int cnt = count(a.begin(), a.end(), a.at(0));
std::cout << a.at(0) << " " << cnt << " times.n";
return 0;
}
编译器标志:
-------------- Build: Debug in test (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -Wall -fexceptions -g -Weffc++ -std=c++14
此外,我的解决方案可能对您有用
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<string> stringList;
stringList.push_back("abc");
stringList.push_back("def");
stringList.push_back("111 abc");
string searchWord ("abc");
int searchWordSize = searchWord.size();
int count = 0;
for (vector<string>::iterator iter = stringList.begin(); iter != stringList.end(); ++iter) {
for (size_t pos = 0; pos < (*iter).length(); pos += searchWordSize) {
pos = (*iter).find(searchWord, pos);
if (pos != string::npos) ++count;
else break;
}
}
cout << "Count: " << count << endl;
return 0;
}
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值