仅获取指定间隔的矢量数据

时间:2014-03-17 05:10:09

标签: c++ vector iterator

我有一个只检索向量中所有元素的代码。我想只检索将赋予函数的指定范围的向量元素。我尝试过迭代器递增但我无法检查我想要向量元素的范围的结尾。 代码:

void calculate(int start, int end)
{
  //Vector dupViewResults is already populated with another function
  //The definition of dupViewresults is vector<vector<string>> dupViewResults

  vector< vector<string> >::iterator row;
  for (row = dupViewResults.begin(); row != dupViewResults.end(); ++row)
  {
    std::advance(row, start); //Setting the iterator to the starting element.
    std::string filedata = readFileDataInStr(row->at(0));
    int x = boost::lexical_cast<int>( row->at(1) );
    long long int fileCRC32 = MurmurHash(filedata.c_str(), x, 0);
    std::string strCRC32 = std::to_string(fileCRC32);
    std::string query = "update duplicatesview set CRC32='" + strCRC32 + "' where Filepath='" + row->at(0) + "'";
    char* charQuery = &query[0];
    db.fireSQLQuery(charQuery, results);
  }
}

在上面的代码中,我不确定如何检查结束位置然后中断。在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

int elementNumbers = dupViewResults.size();
vector< vector<string> >::iterator temp; 
if(end < elementNumbers)
     std::advance(temp, end);
else 
    temp = dupViewResults.end();

if(row > temp) //  check the end position and then brea
    break;

答案 1 :(得分:0)

嗯,我不知道这是否是一个好习惯,但你可以从矢量中检索元素,就像从数组中提取元素一样:

for(int k=0; k< 5; k++)
 cout << VectorName.at[k] << endl;

答案 2 :(得分:0)

为什么不使用它 -

void calculate(int start, int end)
{
    for (int i = start ; i<end && i < dupViewResults.size(); i++)
    {
         //do your stuff with dupViewResults[i]
    }
}