gpt4 book ai didi

c++ - 一种使用 STL 计算 std::string vector 中字符的方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:22 25 4
gpt4 key购买 nike

虽然查找 std::string vector 中的字符数量很简单,但我想知道是否有办法使用 STL 为您完成所有工作,而不是使用两个 for 循环,一个循环遍历 vector ,另一个循环遍历 vector 每个索引中的字符串。

我尝试过使用其他 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();
});

这是一个demo on ideone .

关于c++ - 一种使用 STL 计算 std::string vector 中字符的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17823561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com