c++ - 如果大小等于特定数字,如何找到字符串 vector 的单个索引的大小并打印索引?

标签 c++ vector indexing

我有一个 vector 字符串,现在,例如,如果该索引的大小等于4,我想打印该 vector 的单个索引。

std::vector<string> str = {"Time", "Hello", "User"};
我知道如何遍历 vector 并打印出索引,但是我不知道如何获取例如我要打印到控制台的第一个索引(“时间”)的大小。
这里只需要一些提示:)
谢谢。

最佳答案

看看std::string::size()和如果您对范围循环感到满意

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> str = {"Time", "Hello", "User"};

    for (const auto &s: str)
    {
        if(s.size() == 4) 
        {
            std::cout<<s;
            break;
        }
    }

    return 0;
}
或迭代器
#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> str = {"Time", "Hello", "User"};

    for (auto s = str.begin(); s != str.end(); s++)
    {
        if(s->size() == 4)
        {
            std::cout<<(*s);
            break;
        }
    }

    return 0;
}
希望对您有所帮助,谢谢。

关于c++ - 如果大小等于特定数字,如何找到字符串 vector 的单个索引的大小并打印索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63952494/

相关文章:

c++ - 是否可以使用标签调度来确定返回类型

c++ - C++ 中的继承和友元函数

postgresql - 如何测量 Postgres 索引占用的磁盘空间?

c++ - 计算第三人称摄像机的位置

C++:使用STL vector有什么错误

java - 将元素添加到第一个空数组的索引

mysql - 为什么 MySQL 不在 GROUP BY 查询中使用这个索引?

c++ - 调整QListView的高度以适应内容

c++ - 完整的模板特化不起作用 : no instance of function template "mysort2" matches the specified type STLTests

c++ - 使用 SSE 进行 vector 初始化