C ++ - 计算Occurence并在Vector中传递值

时间:2015-12-13 18:02:14

标签: c++

所以我相信文本文件中的值会进入向量' com,我想要做的是识别方向然后取值旁边的方向,设置为tmp变量,继续读取,如果方向再次出现,添加combine变量然后覆盖tmp变量,将final tmp变量设置为传递给另一个类。如果已经看过重复'它会查看最后使用的方向,并将重复值添加到最后使用的方向,任何帮助都将受到赞赏,对于任何疑问中的混乱感到抱歉

FILE1.TXT:

 Forward 2
 Left 20
 Forward 1
 Repeat 3

fileReader.cpp

#include <iostream> 
#include <float>
#include <vector>

using namespace std;

int main()
{
    ifstream file("text1.txt");     
    string word;
    vector<float> com;

    while (file >> word)
    {
        if(std::find(std.begin(com), std.end(com), Forward) != com.end())
        {
        }

        if(std::find(std.begin(com), std.end(com), Jump) != com.end())
        {
        }

        if(std::find(std.begin(com), std.end(com), Left) != com.end()))
        {
        }

        if(std::find(std.begin(com), std.end(com), Right) != com.end()))
        {
        }

        if ((std::find(std.begin(com), std.end(com), Repeat) != com.end()))
        {
        }
    }       
}

2 个答案:

答案 0 :(得分:0)

您可以使用地图解析输入:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor redColor];
}

代码未经测试。

答案 1 :(得分:0)

好吧,我更喜欢使用不同的容器从头开始重写代码,而不是填充空白:

#include <iostream>
#include <map>
#include <fstream>
#include <string>

int main() {
    std::map<std::string,int> moves{{"Forward", 0}, {"Left", 0}, {"Right", 0},
                                    {"Jump", 0 }, {"Repeat", 0}};

    auto iRepeat = moves.find("Repeat");
    auto iold = moves.end();

    std::ifstream iFile("text1.txt");
    if ( !iFile.good() ) return 1;

    std::string s;
    int x;                       // There aren't floats in your file...
    while ( iFile >> s >> x ) {
        auto im = moves.find(s);
        if ( im == iRepeat ) {
            if ( iold == moves.end() ) continue;    // there must be a move to repeat
            iold->second += x;
        } else if ( im != moves.end() ){
            im->second += x;                        // update the move
            iold = im;
        }
    }

    iFile.close();

    for ( auto i = moves.begin(); i != moves.end(); i++ ) { 
        if ( i != iRepeat )     // shows only the moves
            std::cout << i->first << ": " << i->second << std::endl;
    }

    return 0;
}

输出结果为:

Forward: 6
Jump: 0
Left: 20
Right: 0