小编Onk*_*jan的帖子

c_str的奇怪行为?

我有一个下面的代码片段.我期待输出将是mystring,但奇怪的是它输出垃圾字符.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    string s1("mystring");

    const char* s2 = s1.c_str();

    s1 = "Hi there, this is a changed string s1";

    cout << s2 << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

(1)我最初的想法是,c_str负责分配足够的存储空间来保存的s1,并返回其被分配到该内存块的地址s2,并从这里开始s1,并s2开始了独立.

(2)但当我s1 = "Hi there ..... "在(1)中指出我的想法被证明是错误的.不知何故,s1仍在影响着s2.

(3)当我注释掉s1 = "Hi there .... "线条时,一切正常,即mystring一致打印.

(4)我并不是真的相信我在(1)中的主张c_str是分配内存来保持s1,因为如果是这种情况,我们将不得不通过s2 …

c++

3
推荐指数
2
解决办法
140
查看次数

如何将数组部分初始化为某个默认值?

我有一个数组(例如,,unsigned int arr[1000])。

我想像这样初始化数组的元素..

arr = {4, 10, 34, 45, 6, 67, UINT_MAX, UINT_MAX .. 994 times}
Run Code Online (Sandbox Code Playgroud)

那是在我分配一些值之前,我希望数组中的默认值是 UINT_MAX。

有没有办法做到这一点?

当然 for 循环总是存在的,但除此之外还有其他任何方式。

c++ c++11 c++14 c++20

3
推荐指数
3
解决办法
164
查看次数

正确使用vector&lt;int&gt;::size_type

我在一些关于 C++ 的著名书籍中看到——

vector<int> ivec;

for (vector<int>::size_type i = 0; i != 10; ++i) {
    ivec.push_back(i);
    ivec.push_back(i);  // duplicate copies of each number

}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么vector<int>::size_type在这里使用。他们没有i与向量的大小进行比较。int目的是在向量中插入 10 ,所以这int i = 0是正确的做法,不是吗?

vector<int>::size_type将为,而 又将为typedef,但这里我们将' 存储在 中。std::size_tunsinged intintvector

请澄清我的理解vector<int>::size_type。在上面的 for 循环中使用它公平吗?

c++ c++11

2
推荐指数
1
解决办法
1804
查看次数

如何在 cmake 中使用 DEBUG 宏?

我是 cmake 的新手,所以首先,我很抱歉这个问题太基本了..

问题是,

我有一些日志#ifdef DEBUG,我只想在其下打印调试版本。

像这样的东西..

void func () {

// some code here 

#ifdef DEBUG
    print_log(...) // this portion should execute only for debug builds
#endif 

// some code here

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能用 cmake 实现这一点?

我已经看过#ifdef DEBUG 与 CMake 独立于平台cmakelists 调试标志不执行 "ifdef DEBUG" 内的代码,这里的建议似乎对我不起作用

(项目是在Linux平台上)

c c++ cmake

1
推荐指数
1
解决办法
4337
查看次数

标签 统计

c++ ×4

c++11 ×2

c ×1

c++14 ×1

c++20 ×1

cmake ×1