c++ - 向量的元素不更新
问题描述
//simply print each elements in a vector
template<class Iterp>
void print_iter(Iterp begin, Iterp end, std::string delim=", ", std::string ending="\n"){
int len = (end-begin);
for (size_t i = 0; i < len-1; i++)
{
std::cout << (*(begin+i)) << delim;
}
if (len>1){
std::cout << (*(end-1));
}
std::cout << ending;
}
template<class A, class B>
void pr(A first, A end, std::vector<std::vector<B>> &the_result){
int len = end-first;
for (size_t a = 0; a < len; a++)
{
for (size_t b = 0; b < len; b++)
{
for (size_t c = 0; c < len; c++)
{
//theres a bunch ways i tried to save these in "the_result" variable, and I ended up with this.
std::vector<B> result(first, end);
result.at(a) = (*(first+a));
result.at(b) = (*(first+b));
result.at(c) = (*(first+c));
print_iter(result.begin(), result.end());
//the problem is the "result" variable is not updating using .at() function. So the "result" variable content is still 1, 2, 3.
the_result.push_back(result); //this is not the problem since the "result" variable is still 1, 2, 3
// std::cout << (*(first+a)) << " " << (*(first+b)) << " " << (*(first+c))
// But, this one shows it's producing the right permutations.
}
}
}
}
int main(){
std::vector<int> test{1, 2, 3}; //tried to create the permutations of this
int n = 27; //3^3 = 27
std::vector<std::vector<int>> result(n, std::vector<int>(test.begin(), test.end()));
/*hoping to save all the permutations in "result" variable, each as a vector. ex:
123
113
111
...
*/
pr(test.begin(), test.end(), result);
}
所以我尝试创建一个函数来产生重复元素的排列,并希望将每个排列保存在二维向量中。但是,我什至无法使用 .at() 函数指针元素更新“结果”变量向量。但是当我手动打印它时,它显示它是正确的答案。
我还探索了其他一些有类似问题的 StackOverflow,没有答案对我有用。 向量元素未更新
为什么我的对象向量中的元素在调用对象成员函数之一时没有更新?
取消引用向量指针以访问元素 //尝试使用指针但仍然不起作用
我在哪里犯了错误?
解决方案
你的逻辑有问题:
result.at(a) = (*(first+a));
result.at(b) = (*(first+b));
result.at(c) = (*(first+c));
无论a
、b
和的值是什么c
,您在每次迭代中都将相同的数字分配给相同的元素。它们与您用来初始化的元素相同result
。
对于3
元素,您宁愿需要以下内容:
result[1] = (*(first+a));
result[2] = (*(first+b));
result[3] = (*(first+c));
推荐阅读
- facebook-pixel - 如何在 Facebook 分析中按参数细分 Facebook 自定义事件?
- django - Heroku 没有创建迁移目录?
- reactjs - Reactjs中的意外行为onMouseOver onMouseLeave
- c - 在 C 中为暴力破解生成有序密码
- r - 在 RMarkdown 中的代码旁边添加按钮以隐藏/显示代码
- c++ - std::memcpy 是否使其目的地确定?
- css - 转换后继续文档流: translateY(-50%)
- export - 如何更改导出的 SSRS 报告的文件名
- java - 如何在 Java FXML 应用程序中初始化 DatePicker?
- java - 如何从一个方法中给出 2 种不同的数据类型