为多维向量赋值
Assigning values to multidimensional vector
我正在尝试为多维向量赋值,但我总是从Visual Studio收到"R6010 - abort()"错误。
我想要的是一个二维向量,其中第二维与需要的完全一样大。(很重要,因为我现在不知道有多少输入值,我想稍后使用myvector.at(i).size();
所以简而言之:为什么下面的例子不起作用?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < vector < int > > Vektor;
Vektor.resize(10);
int tmp;
while (true) {
cout << "Please enter a value: " << endl;
cin >> tmp;
int size;
if (tmp > 0 & tmp < 11) {
Vektor.at(tmp - 1).push_back(tmp);
}
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
for (int j = 0; j < size; j++) {
cout << "Value at " << i << " , " << j << " : " << Vektor.at(i).at(j) << endl;
}
}
}
return 0;
}
您在以下行中使用了错误的索引:
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
将行更改为:
| ||
v vv
for (int i = 0; i < 10; i++) {
size = Vektor.at(i).size();
正如@RSahu已经回答的那样,您在循环中使用了错误的索引。为了纠正这些值,我建议您避免使用硬编码值。
这可以通过几种方式完成。通过使用vector.size(),你的代码很容易修复。只需使用这两行而不是您当前的两行:
if (tmp > 0 & tmp <= Vektor.size()) {
for (int i = 0; i < Vektor.size() ; i++) {
另一种打印方式可能是
size_t i = 0;
for (const auto& v : Vektor)
{
size_t j = 0;
for (const auto e : v)
{
cout << "Value at " << i << " , " << j << " : " << e << endl;
++j;
}
++i;
}
相关文章:
- 是否可以使用宏来访问动态数组或向量中的元素或为其赋值
- C++:向量元素赋值导致访问冲突
- 赋值给字符[8]的向量
- 如何从文件中为C++中的向量赋值?
- 在 c++ 中赋值给二维向量
- 为多维向量赋值
- 如何使用向量为字符串赋值
- C++:构造函数中的向量赋值错误
- C++标准是否对向量赋值函数或构造函数提出了明确的要求
- 将赋值运算符与 unique_ptr 向量一起使用
- 常量引用向量向量<向量<long>>赋值不编译
- 两个向量赋值错误
- vector.back() 可以用来为向量的最后一个元素赋值吗?
- C++ 关于为向量<Point> myVariable 赋值
- 通过赋值运算符在索引处插入std::向量
- C++ 布尔向量错误:赋值时"iterator not dereferencable"
- 矢量<int>的赋值和输出向量
- 字符串的C++向量,为什么赋值会导致相同的字符引用
- 将赋值运算符与类实例和向量一起使用
- 在c++中在多个函数之间返回和赋值向量的最佳方法