能否使用迭代器按列遍历vector of vectors并计算各列最长字符串长度?
仅用迭代器计算vector of vectors每列最长字符串长度
可以完全通过迭代器实现,核心思路是并行遍历每行元素与存储列最大长度的容器,避免使用任何索引操作。以下是具体实现代码:
#include <vector> #include <string> #include <algorithm> #include <iostream> int main() { std::vector<std::vector<std::string>> myvec = { { "a", "aaa", "aa"}, {"bb", "b", "bbbb"}, {"cc", "cc", "ccc"} }; // 初始化存储每列最大长度的容器,初始值为0,长度等于列数 std::vector<int> max_lengths(myvec.front().size(), 0); // 遍历每一行(使用const迭代器避免修改原数据) for (auto row_it = myvec.cbegin(); row_it != myvec.cend(); ++row_it) { // 并行遍历当前行的字符串,以及max_lengths的元素 auto len_it = max_lengths.begin(); for (auto str_it = row_it->cbegin(); str_it != row_it->cend(); ++str_it, ++len_it) { // 更新当前列的最大长度 *len_it = std::max(*len_it, static_cast<int>(str_it->size())); } } // 输出结果 for (int len : max_lengths) { std::cout << len << " "; // 输出:2 3 4 } return 0; }
关键说明:
- 用
myvec.front().size()获取列数,初始化max_lengths容器,全程无需索引。 - 外层用
cbegin()/cend()遍历所有行,保证对原数据的只读访问。 - 内层同步使用两个迭代器:
str_it遍历当前行的每个字符串,len_it遍历max_lengths的对应位置,通过同步自增实现列的匹配,完全替代索引的作用。 - 借助
std::max比较当前字符串长度与列现有最大长度,更新容器值。
内容的提问来源于stack exchange,提问作者Namal
相关产品推荐
相关产品推荐

