string vector中使用range-based for loop编译错误,如何解决?
问题分析与解决
编译错误原因
你写的range-based for循环犯了类型匹配的核心错误:
seats是std::vector<std::string>类型,范围for循环遍历它时,每次迭代拿到的是容器里的元素本身(也就是std::string对象)- 但你声明的循环变量是
int& i,试图把std::string类型的元素绑定到int类型的引用上,这完全不符合C++的类型规则,所以编译器直接抛出类型不匹配的错误。
你误解了范围for循环的用法:它不是返回元素的索引,而是直接返回元素本身。传统for循环里的i是你手动声明的索引变量,所以类型是int,但范围for的变量类型必须和容器元素类型一致(或兼容)。
正确写法
直接遍历容器元素的引用,直接赋值即可,不需要额外的s_n变量,代码更简洁:
#include <iostream> #include <vector> typedef std::vector<std::string> massive; using std::cin, std::cout, std::endl; int main() { int N = 0; cin >> N; massive seats(N); // 循环变量是string类型的引用,直接绑定vector里的元素 for (std::string& seat : seats) { cin >> seat; } return 0; }
如果坚持要使用索引方式操作,那还是用传统for循环:
for (int i = 0; i < seats.size(); ++i) { cin >> s_n; seats[i] = s_n; }
内容的提问来源于stack exchange,提问作者Fidelity
相关产品推荐
相关产品推荐

