我试图将向量指针传递给基于范围的 for 循环作为其范围表达式。
以下是基于范围的 for 循环的语法:
attr(optional) for ( init-statement(optional) range-declaration : range-expression )
loop-statement
Run Code Online (Sandbox Code Playgroud)
参考自cppreference.com:
range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration.
begin-expr and end-expr are defined as follows:
If range-expression is an expression of array type, then begin-expr is __range and end-expr is (__range + __bound), where __bound is the …Run Code Online (Sandbox Code Playgroud) 在 Herb Sutter 的 2014 年 CppCon 演讲中,他谈到了如果您不打算转让或共享所有权,则不应在函数声明中使用智能指针。最肯定的是,没有对智能指针的 const 引用。
如果我有一个函数接受智能指针指向的元素,那么实现起来就很容易了。你只需这样做:
void f(int& i) //or int*
{
i++;
}
int main()
{
auto numberPtr = std::make_unique<int>(42);
f(*numberPtr);
}
Run Code Online (Sandbox Code Playgroud)
但我想知道,基于范围的循环是否有最佳实践?
int main()
{
auto numberPtrVec = std::vector<std::unique_ptr<int>>{};
for(int i = 0; i < 5; i++)
numberPtrVec.push_back(std::make_unique<int>(i));
for(auto& i : numberPtrVec)
{
//i++; would be the optimum
(*i)++; //dereferencing is necessary because i is still a reference to an unique_ptr
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法直接捕获当前元素作为引用或原始指针?
对我来说,处理智能指针的引用总是感觉有点不对劲。
i以下代码不会改变for 循环中的内容:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if (target == 0) {return vector<vector<int>>{{}};}
else if (!candidates.size() || target < 0) {return vector<vector<int>>();}
else {
vector<vector<int>> with = combinationSum(candidates, target - candidates[0]);
vector<int> new_vector(candidates.begin() + 1, candidates.end());
vector<vector<int>> without = combinationSum(new_vector, target);
for (auto i : with) {i.push_back(candidates[0]);}
with.insert(with.end(), without.begin(), without.end());
return with;
}
}
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我将其更改为auto& i : with ...,它就会起作用。有理由吗?我认为只有当您使用指向的对象或者您不希望变量(在本例中i)在本地范围内更改时,引用才相关。
void set_fee(Patron p, int fee)
{
for (Patron x : patrons)
{
if (p.get_name() == x.get_name()) x.set_fee(fee);
}
for (int i = 0; i < patrons.size(); i++)
{
if (patrons[i].get_name() == p.get_name()) patrons[i].set_fee(fee);
}
}
Run Code Online (Sandbox Code Playgroud)
这patron只是我创建的一些类,这里的任何函数都不重要,get_name()只是返回对象的名称并将对象的费用set_fee(fee)设置为费用。fee
但是有人知道为什么第一个循环不起作用但第二个循环起作用吗?p我基本上只是想在向量内部查找patrons,一旦找到它,我想更改向量内赞助对象的费用,但第一种方法不起作用,为什么?
以下代码运行正常
#include<iostream>
#include<map>
#include<algorithm>
#include<string>
#include<vector> using namespace std;
int main() {
std::map<int, std::string> m;
m[0] = "hello";
m[4] = "!";
m[2] = "world";
for (std::pair<int, std::string> i : m)
{
cout << i.second << endl;
}
return 0; }
Run Code Online (Sandbox Code Playgroud)
但是,如果我将 for 循环替换为
for (std::pair<int, std::string>& i : m)
{
cout << i.second << endl;
}
Run Code Online (Sandbox Code Playgroud)
不管用。我明白'initializing': cannot convert from 'std::pair<const int,std::string>' to 'std::pair<int,std::string> &'
但是,
for (auto& i : m)
{
cout << i.second << endl;
}
Run Code Online (Sandbox Code Playgroud)
正在工作,而且如果我执行以下操作 …
我想获得用户输入的ID的各个数字的总和。到目前为止,这是我拥有的代码,我的代码可以计算用户输入中的字符数,但我希望它也计算各个数字的总和。
// user prompt for student id
cout << "Type in your student login ID: ";
string studentId;
// user input of student ID
getline(cin, studentId);
// computer output of studentId
cout << "Student ID Sum: " << studentId.length() << endl;
Run Code Online (Sandbox Code Playgroud) 我很困惑 C++ 中的 for 循环和 for every 循环之间有什么区别。我阅读了教程和一些书籍,但我还没有看到每个循环有何不同。对于数组,我看到的示例似乎建议每个循环一次循环遍历整个元素。这可能是基于范围的循环所具有的特殊优势吗?
我尝试用左右范围为基础的for循环中,如果您使用范围为基础,通过矢量循环来运行到超出范围的错误有没有办法避免这种错误,如果您使用的是基于范围的for循环
int main()
{
vector<int> num{ 1,2,3,4,5 };
for (auto i : num)
{
cout << num[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
它显示了这个错误
c++ for-loop outofrangeexception visual-c++ range-based-loop
我创建了一个字符串向量,并想用“基于范围的 for 循环”填充它,但它不起作用。我究竟做错了什么?
\ninvalid initialization of reference of type \xe2\x80\x98int&\xe2\x80\x99 from expression of type \xe2\x80\x98std::__cxx11::basic_string<char>\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n编译器是否不明白我想引用向量元素,而不是字符串?
\n当我使用经典的“for 循环”时,它工作正常(我可以访问向量的所需元素并在那里写入值),但我不明白为什么它不能与基于范围的 for 循环一起使用。我的一段代码:
\n#include <iostream>\n#include <vector>\n\ntypedef std::vector<std::string> massive;\nusing std::cin, std::cout, std::endl;\n\nint main() {\n int N = 0, M = 0;\n std::string s_n = "";\n\n cin >> N;\n\n massive seats(N);\n \n for (int& i: seats) {\n cin >> s_n;\n seats[i] = s_n;\n }\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n 我尝试了一些基于范围的 for 循环来了解这个概念,对于整数数组和向量,它工作得很好。但对于字符向量,我的编译器不会给出任何错误消息或所需的结果,只是一行红点。这是我的代码:
\n#include <iostream>\n#include <vector>\nusing namespace std;\nint main(){\n vector<char> myVector {\'a\', \'b\', \'c\', \'d\'};\n myVector.push_back(\'e\');\n for (auto i : myVector){\n cout << myVector[i] << endl;\n }\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n什么\xe2\x80\x99s错了?我找不到任何东西。当我用整数替换字符时,效果很好。
\n我很好奇为什么我们要这样处理多维数组
for (auto& row : mat1)
{
for (int& elements : row)
{
cin >> elements;
}
}
Run Code Online (Sandbox Code Playgroud)
当我们创建一个名为 elements 的临时变量来遍历行并获取每个值时,为什么要使用 &(pass by ref)。以及 for (auto& row : mat1) 中的 & ,有人可以解释这整个部分的每个细节吗?
using namespace std;
int main()
{
const int row{ 3 }, col{ 3 };
array<array<int, col>, row > mat1;
cout << "Enter matrix 1 elements: ";
for (auto& row : mat1)
{
for (int& elements : row)
{
cin >> elements;
}
}
for (auto& row : mat1) …Run Code Online (Sandbox Code Playgroud)