只给出一个std :: string迭代器,是否可以确定字符串的起点和终点?假设我无法访问字符串对象,因此无法调用string.begin()和string.end(),我所能做的就是递增或递减迭代器并测试值.
谢谢,菲尔
有没有g ++选项可以用NULL const char*检测std :: string的不正确初始化?
我正在将一些int字段转换为std :: string,即:
struct Foo
{
int id;
Foo() : id(0) {}
};
Run Code Online (Sandbox Code Playgroud)
...转换成:
struct Foo
{
std::string id;
Foo() : id(0) {} //oooops!
};
Run Code Online (Sandbox Code Playgroud)
我完全忽略了使用0和g ++初始化错误的'id'初始化时没有给我任何警告.在运行时检测到此错误(std :: string构造函数抛出异常),但我真的想在编译时检测到这些东西.有什么办法吗?
为什么std::string会有find会员功能而std::vector朋友却没有呢?
使用std::find字符串有什么问题吗?
我很久以前用Borland C++编写,现在我正在尝试理解"新"(对我而言)C + 11(我知道,我们在2015年,有一个c + 14 ...但我正在工作在C++ 11项目上)
现在我有几种方法可以为字符串赋值.
#include <iostream>
#include <string>
int main ()
{
std::string test1;
std::string test2;
test1 = "Hello World";
test2.assign("Hello again");
std::cout << test1 << std::endl << test2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
他们都工作.我从http://www.cplusplus.com/reference/string/string/assign/了解到还有其他方法可供使用assign.但对于简单的字符串赋值,哪一个更好?我必须用8 std:string填充100多个结构,我正在寻找最快的机制(我不关心内存,除非有很大的区别)
我有一个名字std::string,我想通过std::ostream接口填充数据,避免字符串副本.
执行此操作涉及副本的一种方法是执行此操作:
bool f(std::string& out)
{
std::ostringstream ostr;
fillWithData(ostr);
out = ostr.str(); // 2 copies here
return true;
}
Run Code Online (Sandbox Code Playgroud)
我需要传递结果out,不能返回 ostr.str().
我想避免副本,out = ostr.str();因为这个字符串可能非常大.
是否有某种方式,可能使用rdbuf()s,将std::ostream缓冲区直接绑定到out?
为了澄清,我很感兴趣的是自动扩展的行为std::string,并std::ostream让来电者不必知道调用之前的大小.
更新:我刚刚意识到无害线out = ostr.str();可能需要2份副本:
str()电话std::string赋值运算符.我需要在std :: string对象中使用已经分配的char*缓冲区(带有字符串内容).经过一些研究后,我发现这几乎是不可能的,std :: string总是拥有自己的私有数据副本.我能想到的唯一剩下的方法就是使用一个自定义分配器来返回已经分配的char缓冲区的地址.为了实现这一点,std :: string应该只使用allocator来分配内存来保存其字符串数据,而不是其他任何内容.是这样的吗?
我的问题与在C++中使用"s"后缀有关?
使用"s"后缀的代码示例:
auto hello = "Hello!"s; // a std::string
Run Code Online (Sandbox Code Playgroud)
同样可以写成:
auto hello = std::string{"Hello!"};
Run Code Online (Sandbox Code Playgroud)
我能够在网上找到"s"后缀应该用于最小化错误并澄清我们在代码中的意图.
因此,使用"s"后缀仅仅是为了代码的读者?或者还有其他优势吗?
尝试实现 C++ 代码,其中我们可以使用非 utf8 字符作为 std::string 内的分隔符。
是否有非 UTF-8 char 之类的东西?
假设我有以下代码:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::
int main()
{
string s1{ "Apple" };
cout << boolalpha;
cout << (s1 == "Apple") << endl; //true
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:系统如何在这两者之间进行检查?s1是一个对象,而"Apple"是C 风格的字符串文字。
据我所知,不能比较不同的数据类型。我在这里缺少什么?
#include<iostream>
#include<string>
template <typename T>
void swap(T a , T b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T1>
void swap1(T1 a , T1 b)
{
T1 temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10 , b = 20;
std::string first = "hi" , last = "Bye";
swap(a,b);
swap(first, last);
std::cout<<"a = "<<a<<" b = "<<b<<std::endl;
std::cout<<"first = "<<first<<" last = "<<last<<std::endl;
int c …Run Code Online (Sandbox Code Playgroud)