12、C++11 for循环使用注意事项

  1. 当使用 for 循环遍历某个序列时,无论该序列是普通数组、容器还是用{ }大括号包裹的初始化列表,遍历序列的变量都表示的是当前序列中的各个元素
  • 并不是迭代器。
  1. 基于范围的 for 循环可以遍历普通数组、string字符串、容器以及初始化列表。除此之外,for 循环冒号后还可以放置返回 string 字符串以及容器对象的函数。
  • 但是不能遍历用指针表示的数组。
  1. 当基于范围的 for 循环遍历的是某函数返回的 string 对象或者容器时,整个遍历过程中,函数只会执行一次。
  //遍历函数返回的 string 字符串
      for (char ch : retStr()) {  //retStr()只执行一次
          cout << ch;
      }
  1. 基于关联式容器(包括哈希容器)底层存储机制的限制:
  • 不允许修改 map、unordered_map、multimap 以及 unordered_multimap 容器存储的键的值;
  • 不允许修改 set、unordered_set、multiset 以及 unordered_multiset 容器中存储的元素的值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,string 类型是一个非常常用的字符串类,可以方便地进行字符串的操作。使用 string 类型需要注意以下几点: 1. 头文件:需要包含 <string> 头文件。 2. 声明:需要使用 std 命名空间,或者在全局范围内使用 using namespace std; 声明。 3. 初始化:可以直接使用字符串字面量或者其他 string 对象初始化。 4. 操作:可以使用常规的字符串操作,如比较、拼接、查找、替换等。 5. 长度:可以使用 size() 或者 length() 方法获取字符串的长度。 6. 遍历:可以使用 for 循环或者迭代器遍历字符串中的每一个字符。 7. 转换:可以使用 c_str() 方法将 string 类型转换为 const char* 类型,或者使用 stoi()、stof() 等方法将 string 类型转换为其他类型。 示例代码: ``` #include <iostream> #include <string> using namespace std; int main() { string s1 = "hello"; string s2("world"); string s3 = s1 + " " + s2; cout << s3 << endl; if (s1 == "hello") { cout << "s1 equals to hello" << endl; } int index = s3.find("world"); if (index != string::npos) { cout << "world found at index " << index << endl; } for (char c : s3) { cout << c << " "; } cout << endl; const char* cstr = s3.c_str(); cout << "cstr: " << cstr << endl; return 0; } ``` 输出结果: ``` hello world s1 equals to hello world found at index 6 h e l l o w o r l d cstr: hello world ``` 需要注意的是,string 类型的底层实现是动态分配的内存,因此在进行大量字符串操作时需要注意内存的使用。同时,由于 string 对象的复制和传递会涉及到内存的拷贝,因此也需要注意效率问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值