将字符串列表插入二维向量

Insert list of strings into 2d vector

我正在尝试获取一个列表,并根据列表中的字符串在二维向量中创建一个新行。我是 c++ 的新手,有几个问题:

1) 我可以遍历列表,并获取迭代器当前所在的字符串吗?如果是这样,我怎样才能将该字符串添加到向量中?

2) 我怎样才能在二维向量中实现它?

3) 初始化 2d 向量时,在插入每个元素时,回推是否能够增加大小?我目前将其初始化为 10,但希望将其初始化为 0,并在插入字符串时增加向量。 (不确定这是否是最佳方法)

std::vector<std::vector<string> >myVector(10, std::vector<string>(10));
std::list<string> myList;
list<string>::iterator i;
inputList(myList);

int vectorRow = 0;
int vectorCol = 0;

//Insert list into vector
for (i = myList.begin(); i != myList.end(); i++) {
    //add to the current row of the vector
    if (*i == "endOfRow"){
        vectorRow++;
        vectorCol = 0;
    } else {
        //add to the column of the vector
     vectorCol++;
    }
}

提前致谢。

std::list<std::string> myList;
inputList(myList);

std::vector<std::vector<std::string>>myVector(1);        
for (const auto& str : myList) 
{
    if (str == "endOfRow")
        myVector.push_back({});
    else
        myVector.back().emplace_back(str);
}

if (myList.empty()) 
    myVector.clear();

// there is no need to update these values inside the loop
int vectorRow = (int)myVector.size();
int vectorCol = (int)myVector.back().size();

1) Am I able to iterate through the list, and grab the string that the iterator is currently at? If so, how am I able to add that string into the vector?

是的。尽管您可以使用更好的语法,但您这样做的方式是正确的。要将它添加到向量中,只需 emplace_back() 或 push_back().

3) When initializing the 2d vector, would pushback work to be able to increase the size as you insert each element?

会的。但是正如您所说,如果您一开始就知道列表的大小,则可以轻松地对其进行初始化以使其更加优化。如果不想初始化vector,但又想保留space,也可以使用vector.reserve()

我认为这里需要更多上下文,但我猜你想要的是这样的:

std::vector<std::vector<string> > myVector(1);
std::list<string> myList;
inputList(myList);

//Insert list into vector
for (list<string>::iterator i = myList.begin(); i != myList.end(); i++) {
    //add to the current row of the vector
    if (*i == "endOfRow"){
        myVector.push_back(std::vector<string>());
    } else {
        //add to the column of the vector
        myVector.back().push_back(*i);
    }
}

1) Am I able to iterate through the list, and grab the string that the iterator is currently at? If so, how am I able to add that string into the vector?

你可以,但你也可以通过取消引用它来获取你的迭代器指向的字符串,例如如果你的迭代器被称为 iter,那么你只需要写 *iter。不过我很困惑,因为你的例子似乎已经这样做了。

2) How am I able to implement that in a 2d vector?

在回答这个问题之前,需要通过解决问题 1 来弄清楚您真正想要做什么。

3) When initializing the 2d vector, would pushback work to be able to increase the size as you insert each element?...

是的。

...I currently initalize it at 10, but would like to initalize it at 0, and increase the vectors as I insert strings. (Not sure if that's the best approach)

是的,使用 push_back 就可以了。如果您知道您将需要大量容量并且担心效率,请考虑使用 vector::reserve.