簡體   English   中英

將向量拆分為向量

[英]Split Vector into Vector of Vectors

目前,我正在處理Yelp的結果文本文件,其中包含餐館和其他一些信息。 飯店的每個元素都由豎線(|)分隔,而飯店的每個元素都由新線(\\ n)分隔。 (請參見下面的示例)。 我正在嘗試將這條線分成多個向量。 較大的向量將保留所有較小的向量,而較小的向量將各自保留餐館之一的信息。 我如何最好地解決這個問題?

這是文件中的幾行:

Meka's Lounge|42.74|-73.69|407 River Street+Troy, NY 12180|http ://www.yelp.com/biz/mekas-lounge-troy|Bars|5|2|4|4|3|4|5
Tosca Grille|42.73|-73.69|200 Broadway+Troy, NY 12180|http ://www.yelp.com/biz/tosca-grille-troy|American (New)|1|3|2|4
Happy Lunch|42.75|-73.68|827 River St+Troy, NY 12180|http ://www.yelp.com/biz/happy-lunch-troy|American (Traditional)|5|2
Hoosick Street Discount Beverage Center|42.74|-73.67|2200 19th St+Troy, NY 12180|http ://www.yelp.com/biz/hoosick-street-discount-beverage-center-troy|Beer, Wine & Spirits|4|5|5|5|5|4

嘗試這樣的事情:

std::vector< std::vector<std::string> > vecRestaurants;

std::ifstream in("restaurants.txt");
std::string line;

while (std::getline(in, line))
{
    std::vector<std::string> info;

    std::istringstream iss(line);
    while (std::getline(iss, line, '|'))
        info.push_back(line);

    vecRestaurants.push_back(info);
}

in.close();

// use vecRestaurants as needed...

話雖如此,假設每個餐廳的字段的含義和順序始終相同,則可以選擇定義一個struct來保存各個字段,然后創建一個structvector ,例如:

struct sRestaurantInfo
{
    std::string name;
    float field2; // ie 42.74, what is this?
    float field3; // ie -73.69, what is this?
    std::string address;
    std::string url;
    std::string type;
    // what are the remaining numbers?
};

std::vector<sRestaurantInfo> vecRestaurants;

std::ifstream in("restaurants.txt");
std::string line;

while (std::getline(in, line))
{
    sRestaurantInfo info;

    std::istringstream iss(line);
    std::getline(iss, info.name, '|');
    std::getline(iss, line, '|'); std::istringstream(line) >> info.field2;
    std::getline(iss, line, '|'); std::istringstream(line) >> info.field3;
    std::getline(iss, info.address, '|');
    std::getline(iss, info.url, '|');
    std::getline(iss, info.type, '|');
    // read the remaining numbers if needed...

    vecRestaurants.push_back(info);
}

in.close();

// use vecRestaurants as needed...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM