在向量C ++中将整数与字符串相关联

时间:2021-12-20 16:36:38

I have a vector Type which contains 100 values: [ 'City', 'Town', 'City', 'City',......, 'Town']

我有一个包含100个值的矢量类型:['City','Town','City','City',......,'Town']

I want to associate/ map each of the string's in this vector with an integer/ double 10 and 20.

我想将此向量中的每个字符串与一个整数/双10和20相关联/映射。

My attempt at the same:

我同样的尝试:

int s = 20;
int o = 10;
for (int q = 0; q < 100; q++) {
    if (Type[q] == 'City') {
        'City' == s;
    }
    else (Type[q] == 'Town'){
        'Town' == o;
    }
}

This does not work. I would appreciate any help on the topic.

这不起作用。我很感激有关该主题的任何帮助。

1 个解决方案

#1


0  

You can use std::map<std::string, int> (or std::map<std::string, double>) like this:

您可以像这样使用std :: map (或std :: map ):

    std::vector<std::string> Type = { "City", "Town", "City", "City", "Town" };
    std::map<std::string, int> m;

    int s = 20;
    int o = 10;
    for (size_t q = 0; q < Type.size(); q++) {
        if (Type[q] == "City") {
            m["City"] = s;
        }
        else if (Type[q] == "Town") {
            m["Town"] = o;
        }
    }

You'll get a map with two values:

你会得到一个有两个值的地图:

{ "City": 20 }, { "Town": 10 }

{“城市”:20},{“城镇”:10}

If you want to have pairs or type and number you can use vector of pairs or tuples:

如果你想拥有对或类型和数字,你可以使用对或元组的向量:

std::vector<std::tuple<std::string, int>> tuples(Type.size());

int s = 20;
int o = 10;
for (size_t q = 0; q < Type.size(); q++) {
    if (Type[q] == "City") {
        tuples[q] = std::make_tuple("City", s);
    }
    else if (Type[q] == "Town") {
        tuples[q] = std::make_tuple("Town", o);
    }
}

You'll get a vector with values:

你会得到一个带有值的向量:

{"City", 20 }, {"Town", 10 }, { "City", 20 }, { "City", 20 }, {"Town", 10 }

{“城市”,20},{“城镇”,10},{“城市”,20},{“城市”,20},{“城镇”,10}

#1


0  

You can use std::map<std::string, int> (or std::map<std::string, double>) like this:

您可以像这样使用std :: map (或std :: map ):

    std::vector<std::string> Type = { "City", "Town", "City", "City", "Town" };
    std::map<std::string, int> m;

    int s = 20;
    int o = 10;
    for (size_t q = 0; q < Type.size(); q++) {
        if (Type[q] == "City") {
            m["City"] = s;
        }
        else if (Type[q] == "Town") {
            m["Town"] = o;
        }
    }

You'll get a map with two values:

你会得到一个有两个值的地图:

{ "City": 20 }, { "Town": 10 }

{“城市”:20},{“城镇”:10}

If you want to have pairs or type and number you can use vector of pairs or tuples:

如果你想拥有对或类型和数字,你可以使用对或元组的向量:

std::vector<std::tuple<std::string, int>> tuples(Type.size());

int s = 20;
int o = 10;
for (size_t q = 0; q < Type.size(); q++) {
    if (Type[q] == "City") {
        tuples[q] = std::make_tuple("City", s);
    }
    else if (Type[q] == "Town") {
        tuples[q] = std::make_tuple("Town", o);
    }
}

You'll get a vector with values:

你会得到一个带有值的向量:

{"City", 20 }, {"Town", 10 }, { "City", 20 }, { "City", 20 }, {"Town", 10 }

{“城市”,20},{“城镇”,10},{“城市”,20},{“城市”,20},{“城镇”,10}