for (vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
int number = *i;
char* c;
itoa(number, c, 10);
result += c;
}
std::cout << result << std::endl;
에 벡터
for (vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
int number = *i;
char* c;
itoa(number, c, 10);
result += c;
}
std::cout << result << std::endl;
에 벡터
당신은 C++ (11)에 std::to_string
사용할 수를 사용할 수 있습니다 코드에 오류가있어
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<int> vec;
for (int i = 0; i < 100; i++)
{
vec.push_back(i);
}
std::string result;
for (std::vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
result += std::to_string(*i);
}
std::cout << result << std::endl;
}
:
당신은 비 초기화 된 문자 포인터 itoa()
를 호출합니다. itoa()
에 유효한 버퍼가 필요하기 때문에 나쁘다. 게다가 itoa()
은 C++ 표준의 일부가 아닙니다.
char*
을 뒤에두고 더 많은 최신 C++ 기능, 특히 문자열 작성자 인 std::stringstream을 사용하면 변환이 강력하며 (종종 + = 연산자보다 빠릅니다). <<
연산자 (문자열 리터럴, 문자열, 모든 종류의 숫자가 될 수 있음)를 사용하여 요소를 푸시하여 문자열을 작성하고, 자체 데이터 형식에 대한 외부 연산자를 통해 확장 할 수 있으며 많은 형식 옵션이 있습니다 16 진수 등)를 입력하고 str()
메서드를 사용하여 내장 문자열을 반환합니다.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::vector<int> vec;
for (int i = 0;i<100;i++)
vec.push_back(i);
std::stringstream ss;
for (auto& number : vec)
ss << number;
std::cout << ss.str() << std::endl;
}
std::accumulate과 같은 소리가 들립니다.
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
auto main() -> int
{
const std::vector<int> vec{ 1, 2, 3 };
const std::string result = std::accumulate(vec.begin(), vec.end(), std::string(),
[](const std::string& s, const int value)
{
return s + std::to_string(value);
});
std::cout << result << std::endl;
}
궁금하다.'auto main() -> int'와'int main()'의 이점은 무엇입니까? – user2328447
아무런 혜택도없고, 내 편의는 눈속임이다. –
그래서 컴파일러 오류가 발생하는 경우 질문에 오류를 포함시키지 않기로 결정한 이유는 무엇입니까? 또한'char * c; itoa (number, c, 10);'어쨌든'c'가 초기화되지 않기 때문에 정의되지 않은 동작입니다. –
예제 코드에 변수 정의를 포함하십시오. 그것과 관련이있을 수 있습니다. – Detonar