一种使用STL计算std::string向量中字符数的方法
A way to use the STL to count chars in a vector of std::string?
因此,虽然查找std::string向量中的字符数量很简单,但我想知道是否有一种方法可以使用STL为您完成所有工作,而不是使用两个for循环,一个循环通过向量,另一个循环通过向量的每个索引中的字符串。
我尝试过使用其他STL函数(例如尝试以几种独特的方式使用std::for_each),但所有的尝试都没有成功。
int main(void)
{
int chars = 0;
std::vector<std::string> str;
str.push_back("Vector");
str.push_back("of");
str.push_back("four");
str.push_back("words");
for(int i = 0; i < str.size(); ++i)
for(int j = 0; j < str[i].size(); ++j)
++chars;
std::cout << "Number of characters: " << chars; // 17 characters
// Are there any STL methods that allows me to find 'chars'
// without needing to write multiple for loops?
}
要开始,不需要第二个循环:
for(int i = 0; i < str.size(); ++i) {
chars += str[i].size();
}
现在是标准库解决方案:
int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) {
return sum + elem.size();
});
这是ideone上的演示。
对于意图明确的解决方案,可以使用std::accumulate
:
using type = std::string::size_type;
type chars = std::accumulate(
std::begin(str), std::end(str), type(0), [](type total, const std::string &s) {
return total + s.length();
}
);
int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) {
return sum + elem.size();
});
相关文章:
- 如何将类值分配给向量<string>?
- 循环遍历向量<string>并保持每个元素"count"时出现问题
- 对 c++ 向量<string>进行排序
- 字符串和向量<string>元素之间的区别
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 如何在 c 中比较和排序向量<string>
- 我可以读取向量<string>::迭代器的数字位置吗?
- .txt向量<string>、非类类型错误
- c_str() 结果从向量<string>变成垃圾与 libc++
- 更改向量<string>中字符串的大小
- 我们可以在C++中将向量<string>放入列表中吗?
- 如何将向量<string>和push_back()格式化为其他向量?
- 加密/解密向量<string>
- QStringList 的 PushBack (push_back()) 元素到向量<string>
- 两个向量<string>串联
- 从向量<string>到 char** 的转换仅携带第一个元素
- 我们可以使用 const_cast 将常量向量转换为<string>向量<string>吗?
- C++ 比较向量<string> X 与字符串 S
- 字符串[]还是向量<string>?
- 比较列表<string>和向量<string>中的字符串元素