gpt4 book ai didi

c++ - 静态 vector 对字符串类成员函数

转载 作者:行者123 更新时间:2023-11-28 04:16:15 25 4
gpt4 key购买 nike

Write a function partlist that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.

据我所知,该函数应该生成原始数组的线性分区(使用 term 作为数学)。

我想我单独理解函数的每种类型,但我很难将它们组合在一起。

(我有 6 个月的 C++ 经验,没有其他语言。这是我用来尝试提高编码技能的 codewars 的练习)

我已经把功能代码写到要开始测试的地步了,但是从问题的措辞来看,我不明白如何实例化类类型。我从类笔记和 cplusplus.com 中以单独的术语复习了静力学、 vector 、对和常量。

我已经知道程序可以编译,但不会完成 main()。我觉得我遗漏了一些重要的信息,感谢任何帮助我理解该计划目标的帮助。

#include <iostream>
#include <vector>
class PartList
{
public:
static std::vector<std::pair <std::string, std::string>> partlist(std::vector<std::string> &arr);
};

///The above is what I have to work with///

int main(){
std::vector<std::string> tester = {"I", "Love", "To", "Discrete"};
PartList::partlist(tester);
}

std::vector<std::pair<std::string,std::string>> PartList::partlist(std::vector<std::string> &arr){
std::vector<std::pair<std::string,std::string>> output;
std::vector<std::pair<std::string,std::string>>::iterator bigIt = output.begin();
std::vector<std::string>::iterator myIt;
for(std::vector<std::string>::iterator secIt = arr.begin();
secIt != arr.end(); secIt++){
myIt = arr.begin();
while(myIt <= secIt){
bigIt->first += *myIt;
myIt++;
}
while((myIt > secIt) && myIt != arr.end()){
bigIt->second += *myIt;
myIt++;
}
}
return output;
}

预期:

对于 set {std::string a, std::string b, std::string c, std::string d}

应该产生 {a, bcd}, {ab,cd}, {abc,d}

结果:

没有

最佳答案

正如约翰在评论中所说。你实际上并没有任何output。在 for 循环的开始,您需要使用 output.push_back() 将新项目附加到 output。然后,不使用迭代器,只需使用 output.back()

引用该项目

代码:

using std::vector;
using std::string;
using std::pair;

vector<pair<string, string>> PartList::partlist(vector<string> &arr)
{
vector<pair<string, string>> output;
vector<string>::const_iterator arr_iterator;

for (vector<string>::const_iterator secIt = arr.begin(); secIt != std::prev(arr.end()); secIt++)
{
arr_iterator = arr.begin();
output.push_back(pair<string, string>());
while (arr_iterator <= secIt)
{
output.back().first += *(arr_iterator++);
}
while (arr_iterator != arr.end())
{
output.back().second += *(arr_iterator++);
}
}
return output;
}

关于c++ - 静态 vector 对字符串类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56532157/

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