簡體   English   中英

在C ++中使用訪問器引用向量進行迭代

[英]Using accessors on reference to vector for iteration in C++

我試圖迭代一個函數內的字符串向量的引用。 代碼最初迭代在向量的內部副本上,但如果可能的話,我想迭代原始代碼。 但是,當我嘗試這樣做時,我會遇到類型不匹配的問題。

我嘗試通過設置和打印它來處理迭代器的一部分,但是我使用%s格式說明符進行初始化和打印時出現類似的類型不匹配。 在gdb內部,打印begin訪問器對於向量的引用或對其自己的向量的副本的作用相同。

外:

std::vector<std::string> foo;
foo.pushback('alpha');
foo.pushback('bravo');
func(foo);

里面有復制:

void func(const std::vector<std::string> &bar){

    std::vector<std::string> barcopy = bar;

    for (std::vector<std::string>::iterator barIt = barcopy.begin(); barIt != barcopy.end(); barIt++){
        //operations with the string inside barcopy
    }
}

里面沒有復制:

void func(const std::vector<std::string> &bar){
    for (std::vector<std::string>::iterator barIt = bar.begin(); barIt != bar.end(); barIt++){
        //operations with the string inside bar
    }
}

我希望引用的行為與副本相同,但在嘗試編譯時嘗試直接獲取以下內容。

error: conversion from 
'__gnu_cxx::__normal_iterator<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >*, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >' 
to non-scalar type 
'__gnu_cxx::__normal_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >*, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >' 
requested

在對向量的引用上執行時,begin訪問器返回什么類型? 如何在不復制的情況下迭代此引用?

因為您將bar作為const ref傳遞,所以需要更改:

for (std::vector<std::string>::iterator barIt = bar.begin(); barIt != bar.end(); barIt++)

至:

for (std::vector<std::string>::const_iterator barIt = bar.cbegin(); barIt != bar.cend(); barIt++)

或者,更好的是,使用一個ranged for循環,如果你想要的是迭代向量中的元素:

for (auto &elem : bar)

或者,將函數簽名更改為void func(std::vector<std::string> &bar) (不帶const )。 范圍for for循環將適用於任何一種情況。

請注意,您將該參數作為const引用。 該錯誤是由於嘗試從const容器中獲取非const迭代器。 您可以通過將代碼更改為:(注意迭代器類型)來修復錯誤

for (std::vector<std::string>::const_iterator barIt = bar.begin(); barIt != bar.end(); barIt++){
    //operations with the string inside bar
}

或者,您可以使用auto關鍵字來推斷正確的迭代器類型:

for (auto barIt = bar.begin(); barIt != bar.end(); barIt++){
    //operations with the string inside bar
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM