如何在C ++中将字符串作为向量中的数据类型?

问题描述 投票:-1回答:2

我想将字符串作为向量中的元素传递,然后将每个值与特定字符进行比较。我得到的问题是“没有匹配的函数要调用”……我已经包括了字符串和向量库。我认为错误很可能是由于向量函数无法处理字符串输入而引起的。

c++ string vector
2个回答
0
投票

我觉得错误很可能是由于向量函数无法处理字符串输入。

是的。如果需要此行为,则需要手动将字符串转换为向量。

std::vector<char> to_vec(const std::string &str)
{
    return {str.begin(), str.end()}; // constructor that copies a range of characters
}

但是,如果您同时需要std::string std::vector的行为,这可能不是理想的解决方案。


0
投票

在我正在使用的最新VS 2019中,它像这样对我有效:

您应该能够访问向量中字符串的索引,就像向量是2D数组一样。

由于“ vecOfstr [0]”是一个字符串变量,而第二个“ [0]”将引用字符串中的索引,因此应该起作用

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

int main()
{
    std::vector<std::string> vecOfstr;
    vecOfstr.push_back("line 01");
    int len = vecOfstr[0].length();
    if (vecOfstr[0][0] == 'l')
        std::cout << "Yes!";
    else
        std::cout << "No!";
    std::cout << "Length of string is:" << len;
}
© www.soinside.com 2019 - 2024. All rights reserved.