首页 > 解决方案 > 关于在csv中写入文件

问题描述

我有一个必须读取的 CSV,并在写入之前删除了重复值。

重复值将基于两列(日期、价格)(AND 条件语句)。因此,在下面的示例中,第 1 行、第 2 行和第 4 行将被写入 CSV。第 3 行将被视为重复(因为相同的日期和价格与第 1 行匹配)并将被排除(未写入 CSV)。

address      floor       date         price
40 B STREET    18        3/29/2015    2200000
40 B STREET    23        1/7/2015     999000
40 B STREET    18        3/29/2015    2200000
40 B STREET    18        4/29/2015    2200000

标签: c++csv

解决方案


您可以使用日期和价格地图来查找重复项。我没有分享完整的代码,但这将为您提供如何做您想做的事情的指针。

1) 创建日期和价格地图。

std::map<std::string, long> dataMap;

2) 从 CSV 中读取一行。在 dataMap 中进行查找。如果key找到(日期),检查value(价格),如果两者都匹配,则它是重复的,您应该忽略此记录。

// Read a line from CSV and parse it to store
// different values in below variables. This should
// be in a loop where each loop will be fetching
// a line from the CSV. The loop should continue till
// you reach end of the input CSV file.
int floorValue;  
std::string addressValue;  
std::string dateValue; 
long priceValue;

// The benefit of using map is observed here, where you  
// can find a particular date in O(log n) time complexity  
auto it = dataMap.find(dateValue)
if (it != dataMap.end())
    if (it->second == priceValue)
        // Ignore this record
else
{
    // Write this entry into another CSV file.  
    // You can later rename this to the original  
    // CSV file, which will give an impression that  
    // your duplicate entries have been removed  
    // from the original CSV file.  
}

推荐阅读