C++ 如何在不知道其宽度的情况下将元素存储在二维向量中?
我有一个一维向量C++ 如何在不知道其宽度的情况下将元素存储在二维向量中?,c++,matrix,vector,2d,C++,Matrix,Vector,2d,我有一个一维向量 std::vector<int> vec1 = {4, 5, 6, 7}; std::vector<std::vector<int>> vec2; 也许我不完全理解这个问题,但我所理解的可以通过一个简单的for循环来实现。只要考虑一下,我们只有3行 没有什么可以解释的 请参阅: #include <iostream> #include <vector> int main() { // 1d vector
std::vector<int> vec1 = {4, 5, 6, 7};
std::vector<std::vector<int>> vec2;
也许我不完全理解这个问题,但我所理解的可以通过一个简单的for循环来实现。只要考虑一下,我们只有3行 没有什么可以解释的 请参阅:
#include <iostream>
#include <vector>
int main() {
// 1d vector with any number of values
std::vector<int> vec1 = { 4, 5, 6, 7 };
//2d vector with 3 rows
std::vector<std::vector<int>> vec2(3);
// Take all elements from vec1 and copy them to vec2, columns first
for (size_t i{}; i < vec1.size(); ++i)
vec2[i % 3].push_back(vec1[i]);
// Output
for (const auto& v : vec2) {
for (const auto& i : v) std::cout << i << "\t";
std::cout << '\n';
}
return 0;
}
仅此而已。您能解释一下vec2[i%3]的for循环是如何工作的吗?@malicization
i%3
在使用3跳转后为您提供剩余部分。在第一次迭代中,i=0
,这意味着表达式是0%3,也就是0。第二次迭代,1%3
,即1。第三次迭代2%3,即2。然后i
重置为0,并继续为0、1、2、0、1、2…非常感谢!
#include <iostream>
#include <vector>
int main() {
// 1d vector with any number of values
std::vector<int> vec1 = { 4, 5, 6, 7 };
//2d vector with 3 rows
std::vector<std::vector<int>> vec2(3);
// Take all elements from vec1 and copy them to vec2, columns first
for (size_t i{}; i < vec1.size(); ++i)
vec2[i % 3].push_back(vec1[i]);
// Output
for (const auto& v : vec2) {
for (const auto& i : v) std::cout << i << "\t";
std::cout << '\n';
}
return 0;
}
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
. . .