C++ 如何在字符串向量中引用字符串的特定字符?

C++ 如何在字符串向量中引用字符串的特定字符?,c++,string,C++,String,我需要对向量数组中每个字符串的字符进行双循环,我一直在想如何使用语法来调用每个元素的每个字符。向量[]操作符将返回std::string&,然后使用std::string的[]操作符将字符作为char& vector[]运算符将返回std::string&,然后使用std::string的[]运算符将字符获取为char& 由于需要迭代向量中的字符串(即多次使用),请创建常量引用: std::vector<std::string> vec { "abc", "efg" }; for(

我需要对向量数组中每个字符串的字符进行双循环,我一直在想如何使用语法来调用每个元素的每个字符。

向量[]操作符将返回std::string&,然后使用std::string的[]操作符将字符作为char&

vector[]运算符将返回std::string&,然后使用std::string的[]运算符将字符获取为char&


由于需要迭代向量中的字符串(即多次使用),请创建常量引用:

std::vector<std::string> vec { "abc", "efg" };
for( size_t i = 0; i < vec.size(); ++i ) {
    const auto &str = vec[i];
    for( size_t j = 0; j < str.length(); ++j )
        std::cout << str[j];
}

否则,您将不得不多次写入vec[i][j],这太冗长了,因为您需要在向量中的字符串上迭代,即多次使用它,创建常量引用:

std::vector<std::string> vec { "abc", "efg" };
for( size_t i = 0; i < vec.size(); ++i ) {
    const auto &str = vec[i];
    for( size_t j = 0; j < str.length(); ++j )
        std::cout << str[j];
}

否则您将不得不多次编写vec[i][j],这太冗长了

这里显示了不同的方法

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

int main()
{
    std::vector<std::string> v = { "Hello", "World" };

    for ( const auto &s : v )
    {
        for ( auto c : s ) std::cout << c;
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto i = v.size(); i != 0; )
    {
        for ( auto j = v[--i].size(); j != 0; ) std::cout << v[i][--j];
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto it1 = v.begin(); it1 != v.end(); ++it1 )
    {
        for ( auto it2 = it1->rbegin(); it2 != it1->rend(); ++it2 ) std::cout << *it2;
        std::cout << ' ';
    }

    std::cout << std::endl;

}    
您可以以各种方式组合这些方法

如果要使用基于范围的for语句更改字符串中的字符,则必须按以下方式编写循环

    for ( auto &s : v )
    {
        for ( auto &c : s ) /* assign something to c */;
    }

这里展示了不同的方法

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

int main()
{
    std::vector<std::string> v = { "Hello", "World" };

    for ( const auto &s : v )
    {
        for ( auto c : s ) std::cout << c;
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto i = v.size(); i != 0; )
    {
        for ( auto j = v[--i].size(); j != 0; ) std::cout << v[i][--j];
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto it1 = v.begin(); it1 != v.end(); ++it1 )
    {
        for ( auto it2 = it1->rbegin(); it2 != it1->rend(); ++it2 ) std::cout << *it2;
        std::cout << ' ';
    }

    std::cout << std::endl;

}    
您可以以各种方式组合这些方法

如果要使用基于范围的for语句更改字符串中的字符,则必须按以下方式编写循环

    for ( auto &s : v )
    {
        for ( auto &c : s ) /* assign something to c */;
    }

UHvec[i][j]?呃。。。vec[i][j]?为了更安全,还可以使用std::couto更安全,还可以使用std::cout