gpt4 book ai didi

c++ - 将字符串添加到 vector> 的问题

转载 作者:行者123 更新时间:2023-11-30 03:16:34 25 4
gpt4 key购买 nike

感谢您花时间阅读本文!我一直在网上练习,遇到了一个我无法解决的问题。

首先,我们输入一个数字,然后输入一些名字。数字是 vector<string> 的大小我们把名字放在哪里。之后,表示vector<string>的元素将被复制到 list<string> .之后,程序应该将名称复制到 vector<set<string>>。其中每个集合 代表一个团队。团队的规模是通过一个公式来确定的,我在计算规模方面没有问题(例如,如果 child 的数量是 10,并且你希望将他们分成三个团队,那么团队的规模应该分别为 4、3、3。)

现在对我来说棘手的部分来了。复制如下:

第一个输入的名字被复制到第一个set<string> .然后,您获取名称中的字母数 并遍历 list<string> 字母数 次。 (如果您到达列表的末尾,迭代器将返回到列表的开头)

您停在的名称将被放入当前集中直到它已满。当您将名称放入相应的集合中时,它就会从列表中删除

我不知道该怎么做。我把名字放在第一个 set<string> 后就卡住了并将其从 list<string> 中删除我不知道如何返回列表开头的迭代器(如果它到达列表末尾),我也不知道如何跳到下一个set<string>。如果当前已满

这是我尝试过的:

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <list>
using namespace std;
int LettersInWord(string s) { // a "letter" is an alphabetic character or a number
int counter = 0;
for(int i = 0; i < s.length(); i++) {
if((s[i] >= 65 && s[i] <= 90) || (s[i] >= 97 && s[i] <= 122) ||
(s[i] >= 48 && s[i] <= 57))
counter++;
}
return counter;
}
int main() {
vector<set<string>> vss(3); // three teams
list<string> names = {{"Name1"}, {"Name2"}, {"Name3"}, {"Name4"}, {"Name5"},
{"Name6"}, {"Name7"}, {"Name8"}, {"Name9"}, {"Name10"}};

vector<int> size_teams = {4, 3, 3};

auto it = names.begin();
string s = *it;
vss[0].insert(*it); // put the first name in the first set
it = names.erase(it); // erase it

int number_of_iterations = LettersInWord(s);

int counter_of_insertions = 0; // this counter keeps track of
// how many strings are inserted in a set, so
// as not to overflow the size

for(int i = 0; i < vss.size(); i++) { // iterate through the vector of sets
int counter_of_iterations = 0; // we compare this to counter_of_insertions
for(auto it = names.begin(); it != names.end(); it++) { // iterate through the list

if(it == names.end())
it = names.begin(); // if iterator is at the end of list, return it to
// beginning
counter_of_iterations = 0;
if(counter_of_iterations == number_of_iterations) {
vss[i].insert(*it); // insert word
counter_of_insertions++;
if(counter_of_insertions == size_teams[i]) i++;
counter_of_insertions = 0;
it = names.erase(it);
number_of_iterations = LettersInWord(*it); // get no of letters in next word
}
}
}
return 0;
}

它所做的只是将名字复制到第一个集合,并且绝对什么都不做

无论我尝试什么,我都无法解决这个问题。有人愿意修改上面的代码吗?对于任何糟糕的措辞、错误或错误,我深表歉意。

注意:必须使用 list<string><vector<set<string>>

感谢任何愿意以任何方式提供帮助的人!

最佳答案

    if(counter_of_iterations == number_of_iterations) {

这条线永远不可能是真的。

在 godbolt 中很容易看到,因为有一大块代码没有被着色(意味着它没有为它生成任何机器代码):

https://godbolt.org/z/_wm8ff

此外,第 39 行也永远不会运行,因为这是它所在的 for 循环的终止情况。

关于c++ - 将字符串添加到 vector<set<string>> 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228876/

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