繁体   English   中英

如何遍历向量中包含的字符串?

[英]How do I iterate through a string contained in a vector?

为了清楚起见,我不是在问如何遍历字符串向量(这是我所有搜索的结果),而是要遍历包含在字符串向量中的字符串。 当尝试从向量中的字符串分配字符串迭代器一个值时,遇到了链接器错误。

下面的代码引用了字符串的const向量。 该函数的目的是颠倒字母和元素的顺序,因此,如果传入包含{“ abc”,“ def”,“ ghi”}的字符串向量,它将对其重新排序并返回包含以下内容的字符串向量{“ ihg”,“ fed”,“ cba”}。 应当注意,该函数在头文件中声明为静态。 当我尝试尝试在for循环中初始化字符串迭代器时,我遇到了一个问题。 我收到一个链接器错误:

"No matching constructor for initialization of 'std::__1::__wrap_iter<char*>'

我以为从向量迭代器通过->访问rbegin()会起作用,但是...我很困惑。 为什么将stringVectorIterator-> rend()分配给string :: reverse_iterator rit时会导致链接器错误?

vector<string>  StringUtility::reverse(const vector<string> &strings)
{
    // Create a vector of strings with the same size vector as the one being passed in.
    vector<string> returnValue( strings.size() );
    vector<string>::const_reverse_iterator stringsVectorIterator;
    size_t returnVectorCounter;

    for (stringsVectorIterator = strings.rbegin(), returnVectorCounter = 0;
         stringsVectorIterator != strings.rend();
         stringsVectorIterator++, returnVectorCounter++)
    {
        // the problem is in the initialization of the string iterator, it creates
        // a linker error.
        for (string::reverse_iterator rit = stringsVectorIterator->rbegin();
             rit != stringsVectorIterator->rend();
             ++rit)
        {
            returnValue[returnVectorCounter].push_back(*rit);
        }
    }
    return returnValue;
};

stringsVectorIterator是一个const迭代器,因此它的目标字符串是const 这意味着你不能得到一个非const在字符串迭代器。

更改内部循环:

 for (string::const_reverse_iterator rit = ...
              ^^^^^^

一切都会好起来的。

在C ++ 11或更高版本中,可以使用auto避免这些麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM