c++ - 你如何做一个 for 循环作为 while 条件?

标签 c++ vector

我必须从通过 vector 的循环中获得结果作为条件,然后对该结果执行任务。

do{result}

我的数据是连续的入站 json 数据,以 7 组的形式剥离了它的 json 属性。 我需要验证 item[2],然后将 item[3] 发送到不同的 vector 。

我的条件是

(for(int b = 2; b < buydat.size(); b+=7);
buydat[b] == "Buy")

我的行动是

do{
    pricedat.push_back(buydat[3]);
}

我的结果可以显示为

for(int d = 0; d < pricedat.size(); ++d){
    cout << pricedat[d] << " " << endl;
}

我的代码:

vector<std::string> buydat;
vector<std::string> pricedat;
for(int b = 2; b < buydat.size(); b+=7){
    do{
        pricedat.push_back(buydat[3]);
    }
    while(
        //(int b = 2; b < buydat.size(); b+=7;)
        buydat[b] == "Buy"
    );
}

我的错误:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

如何将 for 循环结果作为条件? 通过数据循环 7 次 -> 验证到 item[2] -> 将该系列中的 item[3] 发送到 vector 。

最佳答案

根据评论,代码应该是:

vector<std::string> buydat;
vector<std::string> pricedat;
for(int b = 2; b < buydat.size(); b+=7){
    if ( buydat[b] == "Buy" ) { 
      pricedat.push_back(buydat[b+1]); 
    }
}

您的原始代码有一个无限循环,并且还使用了错误的 buydat 数组索引。

关于c++ - 你如何做一个 for 循环作为 while 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138903/

相关文章:

c++ - 为什么 rand_r 没有在 std 中定义?

c++ - 如何将 back_inserter 与转换结合起来,C++

c++ - 在到达新行之前如何运行 while 循环?

c++ - 将列 vector 从矩阵复制到opencv中另一个矩阵的每个列

c++ - 将 *pointer 元素转换为一维数组

c++ - 智能指针: runtime crash in VS 9 running WinXP-Sp3

c++ - 正在运行的线程中的 cstatic 控件的 Redrawwindow

c++ - 拦截 VBA 应用程序之间的消息

c++ - 将 vector<int> 转换为定界字符串

c++ - 在 Map c++​​ 中对 vector 进行排序