使用具有自动范围和结构化绑定的 C++ 迭代向量矩阵?
Iterate matrix of vectors using c++ with auto range and structured binding?
我想做这样的事情:
vector<vector<int>>& matrix; -> [[1, 1], [2, 2]]
for (auto [a, b] : matrix) {
...
}
这不会为我编译。这是正确的方法吗?如果不是,为什么?
上述方法仅适用于在 C++ 中遍历映射。如果 d 是无序映射那么它可以通过下面的代码迭代
for(auto& [a,b] : d)
{
count<< "First" << a.first << "Second" << a.second <<endl;
}
要迭代 vector> 矩阵,在这种情况下,可以使用以下代码,
vector<vector<int>> mat = { {1,1},{2,2} };
for (auto& a : mat) {
for (auto& b : a) {
cout << b << " ";
}
cout <<endl;
}
您只能将结构化绑定用于存储,其位置可以在编译时确定,即将其绑定到数组或类似 class 的存储。 Vector 的数据存储是动态的,你不能绑定到它的内容,由相邻的元素组成。
您可以将该列表绑定到现有类型的成员,例如如果 vector 包含一对,一个元组或任何类似的结构。
#include <string>
#include <vector>
#include <tuple>
#include <iostream>
int main()
{
std::vector<std::tuple<int,int, std::string>>
v = {{1,3,"aa"},{3,5,"bb"}};
for(auto& [a,b,s] : v)
{
std::cout << a << b << s << std::endl;
}
return 0;
}
我想做这样的事情:
vector<vector<int>>& matrix; -> [[1, 1], [2, 2]]
for (auto [a, b] : matrix) {
...
}
这不会为我编译。这是正确的方法吗?如果不是,为什么?
上述方法仅适用于在 C++ 中遍历映射。如果 d 是无序映射那么它可以通过下面的代码迭代
for(auto& [a,b] : d)
{
count<< "First" << a.first << "Second" << a.second <<endl;
}
要迭代 vector> 矩阵,在这种情况下,可以使用以下代码,
vector<vector<int>> mat = { {1,1},{2,2} };
for (auto& a : mat) {
for (auto& b : a) {
cout << b << " ";
}
cout <<endl;
}
您只能将结构化绑定用于存储,其位置可以在编译时确定,即将其绑定到数组或类似 class 的存储。 Vector 的数据存储是动态的,你不能绑定到它的内容,由相邻的元素组成。 您可以将该列表绑定到现有类型的成员,例如如果 vector 包含一对,一个元组或任何类似的结构。
#include <string>
#include <vector>
#include <tuple>
#include <iostream>
int main()
{
std::vector<std::tuple<int,int, std::string>>
v = {{1,3,"aa"},{3,5,"bb"}};
for(auto& [a,b,s] : v)
{
std::cout << a << b << s << std::endl;
}
return 0;
}