2014-11-22 22 views
2

我有一個矢量數據,我需要看它是否有字買進或vrecord [2]你如何模式匹配矢量中的字符串?

第三元素是什麼,尋找一個字符串的出現內最直接的方式出售向量?

數據:

198397685 
2014-11-14 15:10:13 
Buy 
0.00517290 
0.00100000 
0.00100000 
0.00000517 
198398295 
2014-11-14 15:11:14 
Buy 
0.00517290 
0.00100000 
0.00100000 
0.00000517 
203440061 
2014-11-21 16:13:13 
Sell 
0.00825550 
0.00100000 
0.00100000 
0.00000826 

代碼:

vector<std::string> vrecords; 
    while(std::fgets(buff, sizeof buff, fp) != NULL){ 
      vrecords.push_back(buff); 
    } 

    for(int t = 0; t < vrecords.size(); ++t){ 
      cout << vrecords[t] << " "; 
    } 
+1

'if(vrecords [2] ==「Buy」|| vrecords [2] ==「Sell」)'?正則表達式在這裏會過度imo .. – quantdev 2014-11-22 09:04:04

+0

@bro顯示矢量是如何定義的。 – 2014-11-22 09:08:16

+0

vector vrecords; – bro 2014-11-22 09:11:50

回答

2

首先,它是一個壞主意用C I/O系統中的C++。使用C++函數std::getline或類std::basic_istream的成員函數getline和/或get會更好。

考慮到C函數fgets還在字符串中存儲新行字符。你應該刪除它。例如

while (std::fgets(buff, sizeof buff, fp) != NULL) 
{ 
    size_t n = std::strlen(buff); 
    if (n && buff[n-1] == '\n') buff[n-1] = '\0';  
    if (buff[0] != '\0') vrecords.push_back(buff); 
} 

如果載體聲明如下std::vector<std::string>(我希望它沒有聲明,例如std::vector<char *>),那麼你可以寫,而不是

std::string record; 
while (std::getline(YourFileStream, record)) 
{ 
    if (!record.empty()) vrecords.push_back(record); 
} 

在這種情況下找到單詞「買入」是簡單地使用標題<algorithm>中聲明的標準算法std::find。例如

#include <algorithm> 
#include <iterator> 

//... 

auto it = std::find(vrecords.begin(), vrecords.end(), "Buy"); 

if (it != vrecords.end()) 
{ 
    std::cout << "Word \"" << "Buy" 
       << "\" is found at position " 
       << std::distance(vrecords.begin(), it) 
       << std::endl; 
} 

如果你需要找到以下任何話買或賣,那麼你可以使用標準算法std::find_first_of。例如

#include <algorithm> 
#include <iterator> 

//... 

const char * s[] = { "Buy", "Sell" }; 

auto it = std::find_first_of(vrecords.begin(), vrecords.end(), 
           std::begin(s), std::end(s)); 

if (it != vrecords.end()) 
{ 
    std::cout << "One of the words \"" << "Buy and Sell" 
       << "\" is found at position " 
       << std::distance(vrecords.begin(), it) 
       << std::endl; 
} 

如果需要計數有多少在向量這樣的話則可以使用上述aproaches在一個循環或使用標準算法std::countstd::count_ifstd::accumulate或基於for循環的範圍內。 例如

const char * s[] = { "Buy", "Sell" }; 

auto n = std::count_if(vrecords.begin(), vrecords.end(), 
         [&](const std::string &record) 
         { 
          return record == s[0] || record == s[1]; 
         }); 
+0

您的代碼顯示1次購買,但應顯示3.該數據流中有3筆購買。 https://bpaste.net/show/b5c55bcad687 :( – bro 2014-11-22 09:32:06

+0

@bro請閱讀你自己寫的內容:「我有一個向量中的數據,我需要看看它是否有」購買或出售「 – 2014-11-22 09:38:01