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

时间:2017-12-14 23:48:28

标签: string c++11 vector integer double

我有一个包含100个值的矢量类型:['城市','城镇','城市','城市',......,'城镇']

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

我同样的尝试:

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;
    }
}

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

1 个答案:

答案 0 :(得分:0)

您可以使用std::map<std::string, int>(或std::map<std::string, double>),如下所示:

    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;
        }
    }

您将获得包含两个值的地图:

  

{&#34; City&#34;:20},{&#34; Town&#34;:10}

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

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);
    }
}

您将获得一个包含值的向量:

  

{&#34; City&#34;,20},{&#34; Town&#34;,10},{&#34; City&#34;,20},{&#34; City&#34 ;,20},{&#34; Town&#34;,10}