簡體   English   中英

如何告訴編譯器在字符串向量中執行“基於范圍的 for 循環”?

[英]how to tell compiler to do "range based for loop" in string vector?

我創建了一個字符串向量並想用“基於范圍的 for 循環”填充它,但它不起作用。 我究竟做錯了什么?

invalid initialization of reference of type ‘int&’ from expression of type ‘std::__cxx11::basic_string<char>’

編譯器是否不明白我想引用一個向量元素,而不是一個字符串?

當我使用經典的“for 循環”時,它工作正常(我可以訪問向量的所需元素並在其中寫入值),但我不明白為什么它不適用於基於范圍的 for 循環。 我的一段代碼:

#include <iostream>
#include <vector>

typedef std::vector<std::string> massive;
using std::cin, std::cout, std::endl;

int main() {
    int N = 0, M = 0;
    std::string s_n = "";

    cin >> N;

    massive seats(N);
    
    for (int& i: seats) {
        cin >> s_n;
        seats[i] = s_n;
    }

    return 0;
}

將循環替換為

for (std::string& s : seats) {
    cin >> s;
}

簡而言之,這里s是一個遍歷seats元素的引用。

暫無
暫無

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

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