如何在 cpp 中获取特定向量行的大小

How do you get the size of a specific vector row in cpp?

本文关键字:向量 cpp 获取      更新时间:2023-10-16

我不知道为什么,但由于某种原因它不起作用。有没有其他方法可以轻松获取行的大小,这个似乎效率不高。

vector< vector<string> >::iterator row;
vector<string>::iterator col;
for (row = vector.begin(); row != vector.end(); row++)
{
    std::ostringstream value;
    value << vector[*row].size(); //error 
    cout << "The length is" << value << endl;
    value.str("");
    value.clear();

}

错误:与"运算符 []"不匹配(操作数类型为 "std::vector>>"和 'std::vector>') val <<vec[*row].size(); ^

你是你以错误的方式迭代器.. 顺便说一下,更改:

value << vector[*row].size();

跟:

value << *row.size();
/* or value << row->size(); */

关于你的问题,看看这个例子:

typedef vector<vector<string>> Matrix;
/* specific index */ 
const int index = 3; 
Matrix matrix;
Matrix::iterator row = matrix.begin() + index;
cout << row->size();

迭代器视为一种通用指针。 一般规则是,如果您的迭代器it vector<X>::iterator,则*it是一个X&

正如您在程序中所写的那样,row的类型是 vector<vector<string>>::iterator . 这意味着*row是一个vector<string>&,你可以调用它的size()函数:通过(*row).size()或更简单的row->size()