如何连接 std: : string 和 int?

I thought this would be really simple but it's presenting some difficulties. If I have

std::string name = "John";
int age = 21;

How do I combine them to get a single string "John21"?

转载于:https://stackoverflow.com/questions/191757/how-to-concatenate-a-stdstring-and-an-int

csdnceshi61
derek5. Let me add to this: I tried 'str = "hi"; str += 5; cout << str;' and saw no effect. Turns out this calls operator+=(char) and adds a non-printable character.
5 年多之前 回复

29个回答

In C++11, you can use std::to_string, e.g.:

auto result = name + std::to_string( age );

In alphabetical order:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms
weixin_41568196
撒拉嘿哟木头 That's nearly your entire reputation from a single answer!! You lucky bean ;) I think 8 is standard C (of course also C++), but is probably worth differentiating.
接近 2 年之前 回复
csdnceshi68
local-host See tinyurl.com/234rq9u for a comparison of some of the solutions
9 年多之前 回复
csdnceshi54
hurriedly% Apart from the one link you've gfiven, what are you basing your performance comments on?
大约 11 年之前 回复

If you have C++11, you can use std::to_string.

Example:

std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;

Output:

John21
csdnceshi73
喵-见缝插针 How about name += std::to_string(age + 0LL); instead?
3 年多之前 回复
csdnceshi75
衫裤跑路 It would be name += std::to_string(static_cast<long long>(age)); in VC++ 2010 as you can see here
大约 6 年之前 回复

There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:

char intToChar(int num)
{
    if (num < 10 && num >= 0)
    {
        return num + 48;
        //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
    }
    else
    {
        return '*';
    }
}

string intToString(int num)
{
    int digits = 0, process, single;
    string numString;
    process = num;

    // The following process the number of digits in num
    while (process != 0)
    {
        single  = process % 10; // 'single' now holds the rightmost portion of the int
        process = (process - single)/10;
        // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
        // The above combination eliminates the rightmost portion of the int
        digits ++;
    }

    process = num;

    // Fill the numString with '*' times digits
    for (int i = 0; i < digits; i++)
    {
        numString += '*';
    }


    for (int i = digits-1; i >= 0; i--)
    {
        single = process % 10;
        numString[i] = intToChar ( single);
        process = (process - single) / 10;
    }

    return numString;
}

Another easy way of doing it is:

name.append(age+"");
cout << name;
weixin_41568183
零零乙 This is very much wrong.
3 年多之前 回复
csdnceshi50
三生石@ You're decaying the string literal "" to a char* and incrementing that pointer by age. In other words, undefined behavior.
4 年多之前 回复
csdnceshi73
喵-见缝插针 Actually, it does compile but it invokes undefined behavior
6 年多之前 回复
csdnceshi73
喵-见缝插针 I don't get how this got upvoted 5 times...This doesn't even compile!
6 年多之前 回复

Without C++11, for a small integer range, I found this is all I needed:

Declare/include some variant of the following somewhere:

const string intToString[10] = {"0","1","2","3","4","5","6","7","8","9"};

Then:

string str = intToString[3] + " + " + intToString[4] + " = " + intToString[7]; //str equals "3 + 4 = 7"

It works with enums too.

You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

Output:  John5

This problem can be done in many ways. I will show it in two ways:

  1. Convert the number to string using to_string(i).

  2. Using string streams.

    Code:

    #include <string>
    #include <sstream>
    #include <bits/stdc++.h>
    #include <iostream>
    using namespace std;
    
    int main() {
        string name = "John";
        int age = 21;
    
        string answer1 = "";
        // Method 1). string s1 = to_string(age).
    
        string s1=to_string(age); // Know the integer get converted into string
        // where as we know that concatenation can easily be done using '+' in C++
    
        answer1 = name + s1;
    
        cout << answer1 << endl;
    
        // Method 2). Using string streams
    
        ostringstream s2;
    
        s2 << age;
    
        string s3 = s2.str(); // The str() function will convert a number into a string
    
        string answer2 = "";  // For concatenation of strings.
    
        answer2 = name + s3;
    
        cout << answer2 << endl;
    
        return 0;
    }
    

// Hope it helps

csdnceshi56
lrony* thanks to peter mortenson for editing
接近 2 年之前 回复
std::ostringstream o;
o << name << age;
std::cout << o.str();
weixin_41568126
乱世@小熊 this is great, BYT header file is sstream
3 年多之前 回复
#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

Then your usage would look something like this

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [and tested :p ]

共29条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
如何从DLL的导出函数获取std :: string?

<div class="post-text" itemprop="text"> <p>I want to load a custom DLL (C++ one) and call a function that it exports ? Here is my Go code:</p> <pre><code>func main() { dllForGo := syscall.MustLoadDLL("dllForGo.dll") defer dllForGo.Release() getHello:= dllForGo.MustFindProc("getHello") r1, _, err := getHello.Call(0) // also tried with .Call() and still got the same error } </code></pre> <p>Here the C++ code of my DLL:</p> <pre><code> std::string __stdcall getHello(void) { int a = 1; double b = 10; return ("Hello-World !!"+std::to_string(a) + std::to_string(b)); } </code></pre> <p>I tried to force the use of __stdcall (and link a .def file for this, as I thought that maybe __declspec(dllexport) could be a problem ).</p> <p>However, using DUMPBIN, I can see that getHello uses __cdecl calling convention. Is it a problem? </p> <p>And here is the error I get when I run my Go:</p> <pre><code>Exception 0xc0000005 0x1 0x10 0x7fef0591327 PC=0x7fef0591327 syscall.Syscall(0x7fef05910d0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0) D:/Go/src/runtime/syscall_windows.go:172 +0xf9 syscall.(*Proc).Call(0xc00004e420, 0xc000058090, 0x1, 0x1, 0x565520, 0x21, 0x2e06a0, 0x0) D:/Go/src/syscall/dll_windows.go:146 +0x140 main.main() D:/GoLand_Projects/dllLoad/main.go:58 +0x335 rax 0x22fdb8 rbx 0x9 rcx 0x30 rdi 0x9 rsi 0x0 rbp 0x22fdd9 rsp 0x22fd60 r8 0x30303030302e3031 r9 0x7fef1220000 r10 0x22fd90 r11 0x771a1f r12 0xa r13 0x9 r14 0x0 r15 0x0 rip 0x7fef0591327 rflags 0x10202 cs 0x33 fs 0x53 gs 0x2b </code></pre> <p><strong>EDIT</strong></p> <p>The getHello function is actually well executed. I modified it to write to a file:</p> <pre><code> std::string __stdcall getHello(void) { std::ofstream outfile("D:\\test123.txt"); outfile &lt;&lt; "getHello working!" &lt;&lt; std::endl; outfile.close(); int a = 1; double b = 10; return ("Hello-World !!"+std::to_string(a) + std::to_string(b)); } </code></pre> <p>...and the file is written to. So the problem is at after the exported function returns. Which makes me think I need to change something in the Go part to "welcome" the returned std::string.</p> <p><strong>EDIT2</strong></p> <p>If I change the return type of the exported function to <em>void</em> then, the Call return without exception. Could it be an additional hint that it's indeed related to the calling convention ?</p> </div>

不能将参数 1 从“char”转换为“const std::basic_string<_Elem,_Traits,_Ax> &” 如何解决?

代码如下 在utility文件下报错: error C2664: “std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)”: 不能将参数 1 从“char”转换为“const std::basic_string<_Elem,_Traits,_Ax> &” int _tmain(int argc, _TCHAR* argv[]) { ifstream ifs_str("F:/title.txt"); ofstream ofs_str("F:/out_title.txt"); hash_map<const int,vector<string>>map_1; vector<string>vec_1; hash_map<string,set<int>>map_2; set<int>set_2; vector<string>vec_2; string str_line; while(getline(ifs_str,str_line)){ istringstream is_str(str_line); int k; string v; is_str>>k; is_str>>v; vec_1.push_back(v); map_1.insert(hash_map<int,vector<string>>::value_type(k,vec_1)); } int i, j; for (i = 0; i <vec_1.size() ; i++) { for(j = 0;j < vec_1.size() ; j++) if (!map_1.count(vec_1[i][j])){ for(hash_map<const int,vector<string>>::iterator it =map_1.begin(); it!= map_1.end();++it) set_2.insert(it->first); } map_2.insert(hash_map<string,set<int>>::value_type(vec_1[i][j],set_2)); } for(hash_map<string,set<int>>::iterator it_1 =map_2.begin(); it_1 != map_2.end(); ++it_1){ ofs_str<<it_1->first<<"\t"; for(set<int>::iterator it_set = it_1->second.begin(); it_set != it_1->second.end(); ++it_set) ofs_str<<*it_set<<"\t"; ofs_str<<endl; } ifs_str.close(); ofs_str.close(); }

如何将 std: : string 转换为 const char * 或 char * ?

<div class="post-text" itemprop="text"> <p>How can I convert an <code>std::string</code> to a <code>char*</code> or a <code>const char*</code>?</p> </div> <p>转载于:https://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char</p>

初学者,c++ std::string 内存泄漏如何解决

这是我的作业,要求把string转换成大写: #include <iostream> #include <string> void trans(std::string &sss); int main() { using namespace std; string str = "null"; cout << "Enter a string (q to quit): "; while(getline(cin, str) && str != "q") { trans(str); cout << str << endl; cout << "Next string (q to quit): "; } cout << "Bye.\n"; return 0; } void trans(std::string &sss) { for(int i = 0; sss[i] != '\n'; ++i) sss[i] = toupper(sss[i]); } 一开始还能用,后来再试几次就崩溃了,打开任务管理器发现runtime broker.exe占用内存巨大,百度了下说应该是内存泄漏问题,可是我不知道我的程序哪里有内存泄漏的语句,麻烦大家解答一下,十分感谢~~~~

C2440: “delete”: 无法从“std::string”转换为“void*”

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class A { public: virtual ~A() { cout << "call A::~A()" << endl; } }; class B :public A { public: B(int i) { buf =new char[i]; } virtual ~B() { delete[]buf; cout << "call B::~B()" << endl; } private: string buf; }; void fun(A* a) { delete a; } int main() { A* a = new B(10); fun(a); return 0; } 编译后产生的错误 2 IntelliSense: 表达式必须包含指针类型 1 error C2440: “delete”: 无法从“std::string”转换为“void*” 当注释掉 delete[]buf 一行 ,能够编译通过。。。 这是为什么,不理解错误提示,求大侠帮忙看看。

C++ std::function的用法

我想实现std::function定义的函数类型可以传递参数。 参数类型设置为void的时候,语法是没有错的: ``` typedef std::function<void(void)> TestFunc; class Test{ public: void setFunc(TestFunc f){ fn = f; } private: TestFunc fn; }; void test(){ Test t; t.setFunc(func); } void func(){ /*………………*/ } ``` *** 有参数的时候会报语法错误: ```c typedef std::function<void(int,int)> TestFunc; class Test{ public: void setFunc(TestFunc f){ fn = f; } private: TestFunc fn; }; void test(){ Test t; t.setFunc(func); } void func(int i,int j){ /*………………*/ } ``` **显示错误信息**: `不存在从 "void (int i, int j)" 转换到 "std::function<void (int i, int j)>" 的适当构造函数` 请问这是为什么啊~

C++ 不存在从“std::vector<char,std::allocator<char>>" 到char* 的适当转换函数/E0413/C2664

我想把一个字符串vector数组转化为char型vector二维数组,在倒数第二行会出现如题目上说的问题 ``` #include<iostream> #include<vector> #include<string> using namespace std; int main() { int n; cin >> n; vector<string>arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; string::iterator it; for (it = arr[i].begin(); it != arr[i].end(); it++) { if (*it == '-') { arr[i].erase(it); //STL erase函数 it--; } } } vector<vector<char>>arr1(n,vector<char>(7)); for (int i = 0; i < n; i++) { //arr1[i].data = arr[i]; strcpy(**arr**1[i], arr[i].c_str()); } ```

将C ++ std :: chrono :: duration_cast <std :: chrono :: milliseconds>转换为PHP DateTime

<div class="post-text" itemprop="text"> <p>I´m writing an application composed of a C++ process that acquires data and stores it in a Sqlite3 database, and a PHP Web application to analyze that data.</p> <p>Some collected data generates <code>DateTime</code> formats, that are stored on a <code>INTEGER</code> type field on Sqlite3.</p> <p>At the C++ side, the following piece of code is used to generate the timestamps (in milliseconds precision, as I´m dealing with a real time system):</p> <pre><code>int64_t convertTimePointToInt64(const std::chrono::time_point&lt;std::chrono::system_clock&gt; &amp;time) { auto count = time.time_since_epoch(); auto value = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(count); return value.count(); } std::chrono::time_point&lt;std::chrono::system_clock&gt; dt = std::chrono::system_clock::now(); auto valueToStore = convertTimePointToInt64(dt); </code></pre> <p>The <code>valueToStore</code> is then INSERT´ed on Sqlite using SQL (<code>INTEGER</code> type). </p> <p>My problem is when I try to read it on the Web application. I´m using the following PHP code, where <code>$t</code> is the database INTEGER value:</p> <pre><code>$micro = sprintf("%06d",($t - floor($t)) * 1000000); $d = new \DateTime( date('Y-m-d H:i:s.'.$micro, $t) ); $a = $d-&gt;format("Y-m-d H:i:s.u"); </code></pre> <p>I´m getting stange values (1031 in year, for example) that indicates the PHP logic is messy.</p> <p>The C++ code is running very fine (I can store and retrive timestamps and convert it to/back to <code>std::string</code>). I need to fix my PHP code to show the data correctly.</p> <p>Help appreciated.</p> </div>

“类型转换”: 无法从“CString”转换为“std::string”

Mat checkopen; checkopen=imread((string)Path); 在unicode下出现错误 尝试了还是失败 请大家帮忙小白做下转换

请问如何将const uint8_t*转化为std::string类型

请问如何将const uint8_t*转化为std::string类型,本人c++小白,求教各位大神

将整个 ASCII 文件读入 c + + std: : string [ duplicate ]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c" dir="ltr">What is the best way to read an entire file into a std::string in C++?</a> <span class="question-originals-answer-count"> 11 answers </span> </li> </ul> </div> <p>I need to read a whole file into memory and place it in a C++ <code>std::string</code>.</p> <p>If I were to read it into a <code>char[]</code>, the answer would be very simple:</p> <pre><code>std::ifstream t; int length; t.open("file.txt"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the length) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... Do stuff with buffer here ... </code></pre> <p>Now, I want to do the exact same thing, but using a <code>std::string</code> instead of a <code>char[]</code>. I want to avoid loops, i.e. I <strong>don't</strong> want to:</p> <pre><code>std::ifstream t; t.open("file.txt"); std::string buffer; std::string line; while(t){ std::getline(t, line); // ... Append line to buffer and go on } t.close() </code></pre> <p>Any ideas?</p> </div> <p>转载于:https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring</p>

std::ptr_fun: 3 个重载中没有一个可以转换所有参数类型

我的代码如下: std::string &ss_ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } 我不知道为什么会这样提示,是不是还需要添加什么设置和头文件么?

c++内存问题!!!!!!!

#include <iostream> #include <string> #include <vector> using namespace std; int main() { string a, b; int i, x, y; vector<string> v1, v2; while (cin >> a >> b) { for (i = 0; i < v1.size(); i++) { if (v1[i] == a) { x = i; break; } } if (i == v1.size()) x = i; for (i = 0; i < v2.size(); i++) { if (v2[i] == b) { y = i; break; } } if (i == v2.size()) y = i; if (x == v1.size() && y == v2.size()) { cout << b << " registered." << endl; v1.push_back(a); v2.push_back(b); } else if (v1[y] == a && v2[x] == b) { cout << b << " signed in." << endl; } else if (x != v1.size() && y == v2.size()) { cout << "GOTCHA: MAC address already occupied by "; cout << v2[x] << "." << endl; } else { cout << "GOTCHA: " << b << " MAC address not consistent." << endl; } } return 0; } Invalid read of size 8 | at 0x3F8CC9C0D0: std::string::size() const (in /usr/lib64/libstdc++.so.6.0.13) | by 0x40175D: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:2243) | by 0x4012B5: main (main.cpp:30) | Address 0x4c29498 is 8 bytes before a block of size 8 alloc'd | at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298) | by 0x402184: __gnu_cxx::new_allocator<std::string>::allocate(unsigned long, void const*) (new_allocator.h:89) | by 0x401F80: std::_Vector_base<std::string, std::allocator<std::string> >::_M_allocate(unsigned long) (stl_vector.h:140) | by 0x401BBB: std::vector<std::string, std::allocator<std::string> >::_M_insert_aux(__gnu_cxx::__normal_iterator<std::string*, std::vector<std::string, std::allocator<std::string> > >, std::string const&) (vector.tcc:322) | by 0x401877: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:741) | by 0x40122E: main (main.cpp:27) | |Invalid read of size 8 | at 0x3F8CC9C0D3: std::string::size() const (in /usr/lib64/libstdc++.so.6.0.13) | by 0x40175D: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:2243) | by 0x4012B5: main (main.cpp:30) | Address 0xffffffffffffffe8 is not stack'd, malloc'd or (recently) free'd | | |Process terminating with default action of signal 11 (SIGSEGV) | Access not within mapped region at address 0xFFFFFFFFFFFFFFE8 | at 0x3F8CC9C0D3: std::string::size() const (in /usr/lib64/libstdc++.so.6.0.13) | by 0x40175D: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:2243) | by 0x4012B5: main (main.cpp:30) | If you believe this happened as a result of a stack | overflow in your program's main thread (unlikely but | possible), you can try to increase the size of the | main thread stack using the --main-stacksize= flag. | The main thread stack size used in this run was 10485760. |66 bytes in 2 blocks are possibly lost in loss record 3 of 4 | at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298) | by 0x3F8CC9C3C8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC9D19A: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC9D5EB: std::string::reserve(unsigned long) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC7B05A: std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x401431: main (main.cpp:8) | |114 bytes in 2 blocks are possibly lost in loss record 4 of 4 | at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298) | by 0x3F8CC9C3C8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC9D19A: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC9D5EB: std::string::reserve(unsigned long) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x3F8CC7B05A: std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) (in /usr/lib64/libstdc++.so.6.0.13) | by 0x40141F: main (main.cpp:8) 怎么破! 求大神

Dijsktra算法结果出错:terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid

结果:terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid ``` #include <iostream> #include <sstream> #include <string.h> #include <vector> #include<fstream> #define MaxInt 32767 //表示极大值,即∞ #define MVNum 100 //最大顶点数 using namespace std; typedef int ArcType; //假设边的权值类型为整型 int *D=new int[MVNum]; //用于记录最短路的长度 bool *S=new bool[MVNum](); //标记顶点是否进入S集合S={}; int *Path=new int[MVNum]; //用于记录最短路顶点的前驱 //------------图的顶点结构----------------- typedef struct{ char name[100]; char info[1000]; }VertexType; //顶点结构 //------------图的邻接矩阵----------------- typedef struct{ VertexType vexs[MVNum]; //顶点表 ArcType arcs[MVNum][MVNum]; //邻接矩阵 int vexnum,arcnum; //图的当前点数和边数 }AMGraph; int LocateVex(AMGraph G , string vname){ //确定点v在G中的位置 for(int i = 0; i < G.vexnum; ++i) if(G.vexs[i].name== vname) return i; return -1; }//LocateVex //定义字符串分割函数 vector<string> split(const string& str, const string& delim) { vector<string> res; if("" == str) return res; //先将要切割的字符串从string类型转换为char*类型 char * strs = new char[str.length() + 1] ; //不要忘了 strcpy(strs, str.c_str()); char * d = new char[delim.length() + 1]; strcpy(d, delim.c_str()); char *p = strtok(strs, d); while(p) { string s = p; //分割得到的字符串转换为string类型 res.push_back(s); //存入结果数组 p = strtok(NULL,d); } return res; } void CreateUDN(AMGraph &G,char filename[]){ //采用邻接矩阵表示法,创建无向网G FILE *in; char *ch=new char[1000]; char* s; vector<string> res; if((in=fopen(filename,"r"))==NULL){ cout<<"无法打开graph文件!"<<endl; exit(0); } //读取总顶点数,总边数 fgets(s,1000,in); res=split(s, " "); stringstream ss,kk; ss<<res[0]; ss>>G.vexnum; cout<<G.vexnum<<endl; kk<<res[1]; kk>>G.arcnum; cout<<G.arcnum<<endl; //读取顶点信息 for(int i=0;i<G.vexnum;i++){ fgets(s,1000,in); res=split(s, " "); strcpy(G.vexs[i].name, res[0].c_str()); strcpy(G.vexs[i].info, res[1].c_str()); } //读取边的信息 int m,n; for(int i=0;i<G.arcnum;i++){ stringstream zz; fgets(s,1000,in); res=split(s, " "); m = LocateVex(G, res[0]); n = LocateVex(G, res[1]); //确定两个顶点在G中的位置,即顶点数组的下标 zz<<res[2]; zz>>G.arcs[m][n]; //设置边的权重 G.arcs[n][m] = G.arcs[m][n]; zz.str(""); } fclose(in); }//CreateUDN void ShortestPath_DIJ(AMGraph G, int v0){ //用Dijkstra算法求有向网G的v0顶点到其余顶点的最短路径 int v , i , w , min; int n = G.vexnum; //n为G中顶点的个数 for(v = 0; v < n; ++v){ //n个顶点依次初始化 S[v] = false; //S初始为空集 D[v] = G.arcs[v0][v]; //将v0到各个终点的最短路径长度初始化为弧上的权值 if(D[v] < MaxInt) Path [v] = v0; //如果v0和v之间有弧,则将v的前驱置为v0 else Path [v] = -1; //如果v0和v之间无弧,则将v的前驱置为-1 }//for S[v0]=true; //将v0加入S D[v0]=0; //源点到源点的距离为0 /*―初始化结束,开始主循环,每次求得v0到某个顶点v的最短路径,将v加到S集―*/ for(i = 1;i < n; ++i){ //对其余n-1个顶点,依次进行计算 min= MaxInt; for(w = 0; w < n; ++w) if(!S[w] && D[w] < min){ //选择一条当前的最短路径,终点为v v = w; min = D[w]; }//if S[v]=true; //将v加入S for(w = 0;w < n; ++w) //更新从v0出发到集合V?S上所有顶点的最短路径长度 if(!S[w] && (D[v] + G.arcs[v][w] < D[w])){ D[w] = D[v] + G.arcs[v][w]; //更新D[w] Path [w] = v; //更改w的前驱为v }//if }//for }//ShortestPath_DIJ void DisplayPath(AMGraph G, int begin,int temp ){ //显示最短路 //cout<<Path[temp]<<endl; if(Path[temp] != -1){ DisplayPath(G, begin,Path[temp]); cout<<G.vexs[Path[temp]].name<<"-->"; } }//DisplayPath int main() { //cout << "************算法6.10 迪杰斯特拉算法**************" << endl << endl; AMGraph G; int i , j ,fuwu,jd,start, destination; char f1[]={"graph.txt"}; CreateUDN(G,f1); cout <<endl; cout << "*****无向网G创建完成!*****" << endl; for(i = 0 ; i < G.vexnum ; ++i){ for(j = 0; j < G.vexnum; ++j){ if(j != G.vexnum - 1){ if(G.arcs[i][j] != MaxInt) cout << G.arcs[i][j] << "\t"; else cout << "∞" << "\t"; } else{ if(G.arcs[i][j] != MaxInt) cout << G.arcs[i][j] <<endl; else cout << "∞" <<endl; } } }//for cout << "************欢迎来到**************" << endl << endl; cout << " 1.查询景点信息 "<<endl; cout << " 2.问路查询 "<<endl; cout << " 3.退出 "<<endl; cout<<"*****************请选择需要的服务(1-3)****************"<<endl; cin>>fuwu; switch(fuwu){ case 1:cout<<"本校景点有:"<<endl; for(i=0;i<G.vexnum;i++){ cout<<i<<":"<<G.vexs[i].name<<endl; } cout<<"请选择需要查询的景点"<<endl; cin>>jd; cout<<G.vexs[jd].info<<endl; case 2:cout<<"本校景点有:"<<endl; for(i=0;i<G.vexnum;i++){ cout<<i<<":"<<G.vexs[i].name<<endl; } cout<<"请输入您的所在地"<<endl; cin>>start; cout<<"请输入您的目的地"<<endl; cin>>destination; ShortestPath_DIJ(G,start); cout<<"路径是:"; DisplayPath(G,start,destination); cout<<G.vexs[destination].name<<endl<<"最短距离是:"<<endl; cout<<D[destination]<<endl; case 3: exit(0); } return 0; }//main ```

error C2440: “默认参数”: 无法从“const char [7]”转换为“std::string &”

代码如下: 1 #include<iostream> 2 using namespace std; 3 class Student{ 4 string name; 5 public: 6 Student(string& n ="noName") :name(n){} 7 }; 8 class Teacherk{ 9 string name; 10 public: 11 Teacher(string& n = "noName") :name(n){} 12 }; 13 void addCourse(Student& s); 14 void addCourse(Teacher& s); 15 int main(){ 16 addCourse(Teacher("Prof.DingleBerry")); 17 } 第6行和第11行显示代码错误信息 error C2440: “默认参数”: 无法从“const char [7]”转换为“std::string &” 望路过的大侠出手相救^_^

[C++]向map中插入数据,关键字为string,值为list<int>

``` #include<iostream> #include<string> #include<list> #include<map> int main() { std::map<std::string, std::list<int>> words; std::string word; int temp; while (std::cin>>word) { std::list<int> lst; while (std::cin>>temp) { lst.emplace_back(temp); } words.insert(std::pair<std::string, std::list<int>>(word, lst)); } for (const auto &a : words) { std::cout << a.first << "\n"; for (const auto &b : a.second) { std::cout << b << " "; } std::cout << std::endl; } } 设想用户输入时可以这样输入: a 1 2 3 4 5 b 1 2 3 4 5 输出时为: a 1 2 3 4 5 b 1 2 3 4 5 但是在实际使用的时候输出为 a 1 2 3 4 5 请问是什么原因,该怎么改进呢 ```

用硬编码的元素初始化 std: : vector 最简单的方法是什么?

<div class="post-text" itemprop="text"> <p>I can create an array and initialize it like this:</p> <pre><code>int a[] = {10, 20, 30}; </code></pre> <p>How do I create a <code>std::vector</code> and initialize it similarly elegant?</p> <p>The best way I know is:</p> <pre><code>std::vector&lt;int&gt; ints; ints.push_back(10); ints.push_back(20); ints.push_back(30); </code></pre> <p>Is there a better way?</p> </div> <p>转载于:https://stackoverflow.com/questions/2236197/what-is-the-easiest-way-to-initialize-a-stdvector-with-hardcoded-elements</p>

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解!

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解! 目录 博客声明 大数据了解博主粉丝 博主的粉丝群体画像 粉丝群体性别比例、年龄分布 粉丝群体学历分布、职业分布、行业分布 国内、国外粉丝群体地域分布 博主的近期访问每日增量、粉丝每日增量 博客声明 因近期博主写专栏的文章越来越多,也越来越精细,逐步优化文章。因此,最近一段时间,订阅博主专栏的人数增长也非常快,并且专栏价

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

培训班出来的人后来都怎么样了?(二)

接着上回说,培训班学习生涯结束了。后面每天就是无休止的背面试题,不是没有头脑的背,培训公司还是有方法的,现在回想当时背的面试题好像都用上了,也被问到了。回头找找面试题,当时都是打印下来天天看,天天背。 不理解呢也要背,面试造飞机,上班拧螺丝。班里的同学开始四处投简历面试了,很快就有面试成功的,刚开始一个,然后越来越多。不知道是什么原因,尝到胜利果实的童鞋,不满足于自己通过的公司,嫌薪水要少了,选择...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

工作八年,月薪60K,裸辞两个月,投简历投到怀疑人生!

近日,有网友在某职场社交平台吐槽,自己裸辞两个月了,但是找工作却让自己的心态都要崩溃了,全部无果,不是已查看无回音,就是已查看不符合。 “工作八年,两年一跳,裸辞两个月了,之前月薪60K,最近找工作找的心态崩了!所有招聘工具都用了,全部无果,不是已查看无回音,就是已查看不符合。进头条,滴滴之类的大厂很难吗???!!!投简历投的开始怀疑人生了!希望 可以收到大厂offer” 先来看看网...

97年世界黑客编程大赛冠军作品(大小仅为16KB),惊艳世界的编程巨作

这是世界编程大赛第一名作品(97年Mekka ’97 4K Intro比赛)汇编语言所写。 整个文件只有4095个字节, 大小仅仅为16KB! 不仅实现了3D动画的效果!还有一段震撼人心的背景音乐!!! 内容无法以言语形容,实在太强大! 下面是代码,具体操作看最后! @echo off more +1 %~s0|debug e100 33 f6 bf 0 20 b5 10 f3 a5...

不要再到处使用 === 了

我们知道现在的开发人员都使用 === 来代替 ==,为什么呢?我在网上看到的大多数教程都认为,要预测 JavaScript 强制转换是如何工作这太复杂了,因此建议总是使用===。这些都...

什么是a站、b站、c站、d站、e站、f站、g站、h站、i站、j站、k站、l站、m站、n站?00后的世界我不懂!

A站 AcFun弹幕视频网,简称“A站”,成立于2007年6月,取意于Anime Comic Fun,是中国大陆第一家弹幕视频网站。A站以视频为载体,逐步发展出基于原生内容二次创作的完整生态,拥有高质量互动弹幕,是中国弹幕文化的发源地;拥有大量超粘性的用户群体,产生输出了金坷垃、鬼畜全明星、我的滑板鞋、小苹果等大量网络流行文化,也是中国二次元文化的发源地。 B站 全称“哔哩哔哩(bilibili...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

MySQL性能优化(五):为什么查询速度这么慢

前期回顾: MySQL性能优化(一):MySQL架构与核心问题 MySQL性能优化(二):选择优化的数据类型 MySQL性能优化(三):深入理解索引的这点事 MySQL性能优化(四):如何高效正确的使用索引 前面章节我们介绍了如何选择优化的数据类型、如何高效的使用索引,这些对于高性能的MySQL来说是必不可少的。但这些还完全不够,还需要合理的设计查询。如果查询写的很糟糕,即使表结构再合理、索引再...

用了这个 IDE 插件,5分钟解决前后端联调!

点击上方蓝色“程序猿DD”,选择“设为星标”回复“资源”获取独家整理的学习资料!作者 |李海庆我是一个 Web 开发前端工程师,受到疫情影响,今天是我在家办公的第78天。开发了两周,...

大厂的 404 页面都长啥样?最后一个笑了...

每天浏览各大网站,难免会碰到404页面啊。你注意过404页面么?猿妹搜罗来了下面这些知名网站的404页面,以供大家欣赏,看看哪个网站更有创意: 正在上传…重新上传取消 腾讯 正在上传…重新上传取消 网易 淘宝 百度 新浪微博 正在上传…重新上传取消 新浪 京东 优酷 腾讯视频 搜...

【高并发】高并发秒杀系统架构解密,不是所有的秒杀都是秒杀!

网上很多的文章和帖子中在介绍秒杀系统时,说是在下单时使用异步削峰来进行一些限流操作,那都是在扯淡! 因为下单操作在整个秒杀系统的流程中属于比较靠后的操作了,限流操作一定要前置处理,在秒杀业务后面的流程中做限流操作是没啥卵用的。

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

Java14 新特性解读

Java14 已于 2020 年 3 月 17 号发布,官方特性解读在这里:https://openjdk.java.net/projects/jdk/14/以下是个人对于特性的中文式...

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

疫情后北上广深租房价格跌了吗? | Alfred数据室

去年3月份我们发布了《北上广深租房图鉴》(点击阅读),细数了北上广深租房的各种因素对租房价格的影响。一年过去了,在面临新冠疫情的后续影响、城市尚未完全恢复正常运转、学校还没开学等情况下...

面试官给我挖坑:a[i][j] 和 a[j][i] 有什么区别?

点击上方“朱小厮的博客”,选择“设为星标”后台回复&#34;1024&#34;领取公众号专属资料本文以一个简单的程序开头——数组赋值:int LEN = 10000; int[][] ...

又一起程序员被抓事件

就在昨天互联网又发生一起让人心酸的程序员犯罪事件,著名的百度不限速下载软件 Pandownload PC 版作者被警方抓获。案件大致是这样的:软件的作者不仅非法盗取用户数据,还在QQ群进...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

太狠了,疫情期间面试,一个问题砍了我5000!

疫情期间找工作确实有点难度,想拿到满意的薪资,确实要点实力啊!面试官:Spring中的@Value用过么,介绍一下我:@Value可以标注在字段上面,可以将外部配置文件中的数据,比如可以...

Intellij IDEA 美化指南

经常有人问我,你的 IDEA 配色哪里搞的,我会告诉他我自己改的。作为生产力工具,不但要顺手而且更要顺眼。这样才能快乐编码,甚至降低 BUG 率。上次分享了一些 IDEA 有用的插件,反...

【相亲】96年程序员小哥第一次相亲,还没开始就结束了

颜值有点高,条件有点好

太厉害了,终于有人能把TCP/IP 协议讲的明明白白了

一图看完本文 一、 计算机网络体系结构分层 计算机网络体系结构分层 计算机网络体系结构分层 不难看出,TCP/IP 与 OSI 在分层模块上稍有区别。OSI 参考模型注重“通信协议必要的功能是什么”,而 TCP/IP 则更强调“在计算机上实现协议应该开发哪种程序”。 二、 TCP/IP 基础 1. TCP/IP 的具体含义 从字面意义上讲,有人可能会认为...

腾讯面试题: 百度搜索为什么那么快?

我还记得去年面腾讯时,面试官最后一个问题是:百度/google的搜索为什么那么快? 这个问题我懵了,我从来没想过,搜素引擎的原理是什么 然后我回答:百度爬取了各个网站的信息,然后进行排序,当输入关键词的时候进行文档比对……巴拉巴拉 面试官:这不是我想要的答案 我内心 这个问题我一直耿耿于怀,终于今天,我把他写出来,以后再问,我直接把这篇文章甩给他!!! 两个字:倒排,将贯穿整篇文章,也是面试官...

你怎么看欧阳娜娜空降阿里p8?

前段时间 欧阳娜娜空降阿里P8被骂上热搜 有网友调侃道: 名牌大学毕业的研究生 要在阿里没日没夜、加班加点、 全年无休奋斗5年,才可能有机会 和20岁的欧阳娜娜一起喝下午茶…… 本来嘛,大厂✖明星的营销无可厚非 那是什么让撸代码N年的程序员愤愤不平呢? 还不是因为升到P8真的太难了! 这是很多阿里人甚至互联网人遥不可及的梦想! 阿里P8到底有多牛? 根据知乎大V@半佛仙人透露的情况: 阿里P8基本上要求研究生 5 年以上经验,本科 7 年以上经验; P8 一般去小公司就是各种 O,一般公司(非国企、.

程序员因没转发公司内容,被领导扣500,辞职后:加了三行代码

现如今,程序员在一二线城市可谓是非常的抢手,毕竟年薪那么多,一般在工作了几年之后,程序员想要攒到一套房子的首付是不成问题的,所以一些大龄的女青年在相亲的时候要把程序员当成了首选。但表面上看起来风光的程序员,背地里也受了非常多的委屈,最近有一名程序员没有转发公司的内容到朋友圈被领导扣了500块,当他辞职了之后,却非常淡定。 从个这个帖子中,我们可以看出这名程序员的情绪还是比较激动的,因为没有转发公司的内容到朋友圈,就要被罚款500块,这是非常不合理,换做是别人也不肯接受,而且三次没有转发就要被劝退,这是什么

相关热词 c# cad插入影像 c#设计思想 c#正则表达式 转换 c#form复制 c#写web c# 柱形图 c# wcf 服务库 c#应用程序管理器 c#数组如何赋值给数组 c#序列化应用目的博客园
立即提问