c ++ - 如何从向量<string>中提取第一个元素,并在循环中将向量大小减少1

时间:2017-01-25 17:08:15

标签: c++ vector

string line= "";
vector<string> tokens;
//populate the vector 'tokens'

//loop through vector 'tokens' until it becomes empty
{
    //extract out 'line' containing the first element of the vector.
    //reduce the size of 'tokens' by one through deleting the first element 
}
//use 'line' string one by one in the subsequent code 

假设代币&#39;包含两个元素,例如

  猫,狗,公牛

在第一次迭代中,我想要提取“猫”。从向量中移出并将其大小减小1。 它现在将包含:

  狗,公牛

现在,我想使用这个提取的元素&#39; cat&#39; (存储在字符串&#39; line&#39;中)在我的后续代码中。 下次我想选择“狗”#39;并使向量仅包含

  

。等等。 提前感谢您的想法!

4 个答案:

答案 0 :(得分:3)

当在容器上进行迭代以清空它时,只要容器不为空,就更容易进行迭代。

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> tokens = {"cat", "dog", "bull"};
    while(tokens.empty() == false)
    {
        // Extract the data from first element in the list
        auto line = std::move(tokens.front());

        // Pop the moved element from the vector
        tokens.erase(tokens.begin());

        // Do work with 'line'
        std::cout << line << '\n';
    }

    return 0;
}

也就是说,从向量的前面移除元素是非常低效的,因为所有后续元素都必须向上移动。请考虑从后面删除元素。

答案 1 :(得分:0)

tokens.erase(tokens.begin());

就是这样。

答案 2 :(得分:0)

std :: vector提供了你在另一端看起来想要的操作......

std::vector<std::string>  tokens;

// the last token can be accessed: 
std::string tok = tokens.back();

// removing the last tok
assert(tokens.size());  // pop_back on an empty vector is UB
tokens.pop_back();      // removes element from vector - constant time!

// and if you get confused on how to load tokens in reverse order
// you can load as planned, then reverse the elements to do your work
std::reverse(std::begin(tokens), std::end(tokens))

试一试。我发现在矢量背面易于适应。

答案 3 :(得分:0)

惯用法是:

std::vector<std::string> tokens;
// populate the vector 'tokens'
// ...

for (const auto& token : tokens) {
    // use 'token' string one by one in the subsequent code, as:
    std::cout << token << std::endl;
}
tokens.clear(); // If needed.