gpt4 book ai didi

c++ - 将字符串数组转换为整数数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:20 25 4
gpt4 key购买 nike

我有以下字符串数组:

std::string names_str[7] = {"Alex","Louis","Alex","Simon","Matthew", "Carl", "Simon"};

我想创建一个新的整数数组,大小相同,每个索引元素应该等同于原始字符串数组中的字符串元素。最终结果应该是这样的:

int names[7] = {0, 1, 0, 2, 3, 4, 2};

我如何实现一种算法,以这种方式用数字填充我的整数数组?

我已经开始使用这样的伪代码,但到目前为止它完全没有意义:

for (int i = 0; i < 7; i++) {
int counter = 0;
if names_str[i] has already been used
names[i] = assign the number
else
names[i] = counter;
counter++;
}

最佳答案

您可以使用 std::map跟踪已知的字符串计数器,例如:

#include <string>
#include <map>

std::string names_str[7] = {"Alex", "Louis", "Alex", "Simon", "Matthew", "Carl", "Simon"};
int names[7];

std::map<std::string, int> counter_map;
int counter = 0;

for (int i = 0; i < 7; ++i)
{
auto iter = counter_map.find(names_str[i]);
if (iter == counter_map.end())
iter = counter_map.insert(std::make_pair(names_str[i], counter++)).first;
names[i] = iter->second;
}

Live Demo

或者,由于 insert() 返回一个 iterator 到现有的键控元素,如果键已经存在,你可以通过 find() 避免冗余搜索:

#include <string>
#include <map>

std::string names_str[7] = {"Alex", "Louis", "Alex", "Simon", "Matthew", "Carl", "Simon"};
int names[7];

std::map<std::string, int> counter_map;
int counter = 0;

for (int i = 0; i < 7; ++i)
{
auto ret = counter_map.insert(std::make_pair(names_str[i], counter));
if (ret.second) ++counter;
names[i] = ret.first->second;
}

Live Demo

无论哪种方式,因为你想将一个数组“转换”为另一个相同大小的数组,这是 std::transform() 的一个很好的用例。 :

#include <string>
#include <map>
#include <algorithm>

std::string names_str[7] = {"Alex", "Louis", "Alex", "Simon", "Matthew", "Carl", "Simon"};
int names[7];

std::map<std::string, int> counter_map;
int counter = 0;

std::transform(std::begin(names_str), std::end(names_str), std::begin(names),
[&](const std::string &name) {
auto iter = counter_map.find(name);
if (iter == counter_map.end())
iter = counter_map.insert(std::make_pair(name, counter++)).first;
return iter->second;
}
);

Live demo

#include <string>
#include <map>
#include <algorithm>

std::string names_str[7] = {"Alex", "Louis", "Alex", "Simon", "Matthew", "Carl", "Simon"};
int names[7];

std::map<std::string, int> counter_map;
int counter = 0;

std::transform(std::begin(names_str), std::end(names_str), std::begin(names),
[&](const std::string &name) {
auto ret = counter_map.insert(std::make_pair(name, counter));
if (ret.second) ++counter;
return ret.first->second;
}
);

Live Demo

关于c++ - 将字符串数组转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com