简体   繁体   English

在C ++中从多维向量创建和获取值时遇到问题

[英]Problems creating and getting values from multidimensional vectors in C++

I am having problems creating and getting values from a multidimensional array in C++. 我在C ++中从多维数组创建和获取值时遇到问题。 I have spent quite some time trying to figure out why this is not compiling. 我花了很多时间试图弄清楚为什么不编译。 What's wrong here? 怎么了

The code is as follows; 代码如下: vector<vector<string>> vec; vec[0][0] = "asd"; cout << vec[0][0] << endl;

You may not assign a value to an empty vector using the subscript operator. 您不能使用下标运算符将值分配给空向量。

You could use methods like emplace_back or push_back or insert 您可以使用emplace_backpush_back类的方法,也可以使用insert

For example 例如

std::vector<std::vector<std::string>> vec;

vec.emplace_back( 1, "asd" );
vec.push_back( { 1, "fgh" } );
vec.insert( vec.end(), { 1, "jkl" } );

std::cout << vec[0][0] << std::endl;
std::cout << vec[1][0] << std::endl;
std::cout << vec[2][0] << std::endl;

Or you could initially create the vector with the required number of elements. 或者,您可以最初使用所需数量的元素创建向量。 And in this case you may use the subscript operator. 在这种情况下,您可以使用下标运算符。

For example 例如

std::vector<std::vector<std::string>> vec( 1, std::vector<std::string>( 1 ) );

vec[0][0] = "asd";

std::cout << vec[0][0] << std::endl;

There are many ways to do the task. 有很多方法可以完成任务。 For example you could use the following approach 例如,您可以使用以下方法

std::vector<std::vector<std::string>> vec;
vec.resize( 1 );
vec[0].resize( 1 );

vec[0][0] = "asd";

std::cout << vec[0][0] << std::endl;

You should read the documentation of the constructor. 您应该阅读构造函数的文档。 When you do this: 执行此操作时:

vector<string> vec;
vec[0] = "asd";
cout << vec[0] << endl;

You have UB twice, because you are trying to access an element in the vector, that does not exist. 您有两次UB,因为您正尝试访问向量中不存在的元素。 The first line just creates an empty vector. 第一行只是创建一个空向量。 You either want to push new elements: 您要么要推送新元素:

vector<string> vec;
vec.push_back("asd");
cout << vec[0] << endl;

or pass the size to the constructor: 或将大小传递给构造函数:

size_t start_size=10;
vector<string> vec(start_size);
vec[0] = "asd";
cout << vec[0] << endl;

For 2D this would be: 对于2D,这将是:

typedef vector<vector<string>> MAT;
MAT mat;
vector<string> vec;
vec.push_back("asd");
mat.push_back(vec);
cout << mat[0][0] << endl;

or: 要么:

size_t start_size=10;
MAT mat = MAT(start_size,vector<string>(start_size));
mat[0][0] = "asd";
cout << mat[0][0] << endl;

However, using a vector<vector<T>> is in general not advisable. 但是,通常不建议使用vector<vector<T>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM