【问题标题】:Associating a integer to string in a vector C++将整数与向量 C++ 中的字符串相关联
【发布时间】:2018-05-29 03:53:53
【问题描述】:

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

我想将此向量中的每个字符串与整数/双精度 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;
    }
}

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

【问题讨论】:

  • 这是根本错误的代码。
  • 感谢您的评论。有没有办法将数字映射到字符串?我还必须提到,我是初学者。

标签: string c++11 vector integer double


【解决方案1】:

您可以像这样使用std::map&lt;std::string, int&gt;(或std::map&lt;std::string, double&gt;):

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

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

{ "城市": 20 }, { "城镇": 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);
    }
}

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

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

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2016-03-20
    相关资源
    最近更新 更多